@xmruibi
2015-02-15T02:24:04.000000Z
字数 2722
阅读 716
Data_Structure
Collection: Interface;
AbstractCollection: Abstract Class, reduced workload of Collection interface;
// 所谓 collection骨干实现!
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;// still confused... why minus 8??public abstract Iterator<E> iterator();//return iteratorpublic abstract int size();//size of container(collection)
public boolean contains(Object o) {Iterator<E> it = iterator();// Get Current Iteratorif (o==null) { // Be aware of checking null valuewhile (it.hasNext()) //if (it.next()==null)return true;} else { //Check non-nullwhile (it.hasNext())if (o.equals(it.next()))//judge equiavalentreturn true;}return false;}
Return collection as an array.
public Object[] toArray() {Object[] r = new Object[size()];//allocate array by sizeIterator<E> it = iterator();for (int i = 0; i < r.length; i++) {if (! it.hasNext()) // end iteration if no more elementreturn Arrays.copyOf(r, i);// to make sure the size is fit without space waster[i] = it.next();}return it.hasNext() ? finishToArray(r, it) : r;//for thread safety}
public <T> T[] toArray(T[] a) {int size = size();// make sure the collection size is bigger than a's length, otherwise generate a new array// notice the reflection to gurantee the element typeT[] r = a.length >= size ? a :(T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);Iterator<E> it = iterator();for (int i = 0; i < r.length; i++) {if (! it.hasNext()) { //no more elementif (a == r) {r[i] = null;} else if (a.length < i) {return Arrays.copyOf(r, i);//when the a has no enough space copy array for expand} else {System.arraycopy(r, 0, a, 0, i);if (a.length > i) {a[i] = null;}}return a;}r[i] = (T)it.next();//迭代器赋值元素}return it.hasNext() ? finishToArray(r, it) : r;}private static <T> T[] finishToArray(T[] r, Iterator<?> it) {//notice the static, but why?????int i = r.length;while (it.hasNext()) {int cap = r.length;if (i == cap) {//进行扩容int newCap = cap + (cap >> 1) + 1;//1.5 timesif (newCap - MAX_ARRAY_SIZE > 0) // same step as arraylist resize?newCap = hugeCapacity(cap + 1);r = Arrays.copyOf(r, newCap);}r[i++] = (T)it.next();}return (i == r.length) ? r : Arrays.copyOf(r, i);}
public void clear() {Iterator<E> it = iterator();while (it.hasNext()) {it.next();it.remove();}}// print collection with "[" "]"?public String toString() {Iterator<E> it = iterator();if (! it.hasNext())return "[]";StringBuilder sb = new StringBuilder();sb.append('[');for (;;) {E e = it.next();sb.append(e == this ? "(this Collection)" : e);if (! it.hasNext())return sb.append(']').toString();sb.append(',').append(' ');}}