import java.util.GregorianCalendar; publicclassObjectDemo { publicstaticvoidmain(String[] args) { // create a new ObjectDemo object GregorianCalendarcal=newGregorianCalendar(); // print current time System.out.println("" + cal.getTime()); // print the class of cal System.out.println("" + cal.getClass()); // create a new Integer Integeri=newInteger(5); // print i System.out.println("" + i); // print the class of i System.out.println("" + i.getClass()); } }
执行结果:
1 2 3 4
Mon Oct 11 09:30:37 UTC 2021 class java.util.GregorianCalendar 5 class java.lang.Integer
/** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return {@code true} (as specified by {@link Collection#add}) */ publicbooleanadd(E e) { modCount++; add(e, elementData, size); returntrue; }
/** * This helper method split out from add(E) to keep method * bytecode size under 35 (the -XX:MaxInlineSize default value), * which helps when add(E) is called in a C1-compiled loop. */ privatevoidadd(E e, Object[] elementData, int s) { if (s == elementData.length) elementData = grow(); elementData[s] = e; size = s + 1; }
/** * Increases the capacity to ensure that it can hold at least the * number of elements specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity * @throws OutOfMemoryError if minCapacity is less than zero */ private Object[] grow(int minCapacity) { //记录当前底层数组的长度 intoldCapacity= elementData.length; //如果底层数组的长度大于0或者是底层数组并不是空数组,那么就执行扩容操作 if (oldCapacity > 0 || elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { //将newCapacity设置为minCapacity和1.5*oldCapacity中的最大值 intnewCapacity= ArraysSupport.newLength(oldCapacity, minCapacity - oldCapacity, /* minimum growth */ oldCapacity >> 1/* preferred growth */); //生成了新的数组对象,将原数组中的内容拷贝到新的数组中 returnelementData= Arrays.copyOf(elementData, newCapacity); } else { //底层数组长度为小于等于0或者底层数组为空,那么就将底层数组变成一个容量最小为10的空数组(可以看到下图minCapacity=1,也就是初始化之后如果调用add方法,是会将arraylist扩容为10) returnelementData=newObject[Math.max(DEFAULT_CAPACITY, minCapacity)]; } }
/** * Increases the capacity to ensure that it can hold at least the * number of elements specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity * @throws OutOfMemoryError if minCapacity is less than zero */ //真正实现扩容的函数 private Object[] grow(int minCapacity) { //获得当前的实际容量 intoldCapacity= elementData.length; if (oldCapacity > 0 || elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { //将newCapacity设置为minCapacity和1.5*oldCapacity中的最大值 intnewCapacity= ArraysSupport.newLength(oldCapacity, minCapacity - oldCapacity, /* minimum growth */ oldCapacity >> 1/* preferred growth */); //生成了新的数组对象,将原数组中的内容拷贝到新的数组中 returnelementData= Arrays.copyOf(elementData, newCapacity); } else { //初始化为默认容量 returnelementData=newObject[Math.max(DEFAULT_CAPACITY, minCapacity)]; } }