publicintindexOf(Object o) { // 添加if else 判定可以防止下面空指针异常 // 两个都是for循环到结尾,对于null用==来判定,对于非null用equals来判定 // 只会返回找到的第一个 if (o == null) { for (inti=0; i < size; i++) if (elementData[i]==null) return i; } else { for (inti=0; i < size; i++) if (o.equals(elementData[i])) return i; } return -1; }
toArray
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// 返回一个复制的数组 public Object[] toArray() { return Arrays.copyOf(elementData, size); }
// 传入一个数组,用来装elementData public <T> T[] toArray(T[] a) { // 如果传入的数组长度小于 elementData 的长度 if (a.length < size) // Make a new array of a's runtime type, but my contents: // 返回一个新的数组 return (T[]) Arrays.copyOf(elementData, size, a.getClass()); // 将elementData 装进a里 System.arraycopy(elementData, 0, a, 0, size); // a 末尾设置null,用于标记,表名此处为一个分界点,防止拿到一些原数组的数据,让复制的数据更加安全 if (a.length > size) a[size] = null; return a; }
clear
1 2 3 4 5 6 7 8 9 10
publicvoidclear() { modCount++;
// clear to let GC do its work // 全部设置成null,让gc回收 for (inti=0; i < size; i++) elementData[i] = null; // 重置size size = 0; }
publicbooleanremoveIf(Predicate<? super E> filter) { Objects.requireNonNull(filter); // figure out which elements are to be removed // any exception thrown from the filter predicate at this stage // will leave the collection unmodified intremoveCount=0; // 通过BitSet来记录需要移出数据的下标 finalBitSetremoveSet=newBitSet(size); // 修改次数 finalintexpectedModCount= modCount; // 原elementData容量大小 finalintsize=this.size; // 开始遍历,modCount == expectedModCount 防止并发修改 for (int i=0; modCount == expectedModCount && i < size; i++) { @SuppressWarnings("unchecked") finalEelement= (E) elementData[i]; // 是否满足test if (filter.test(element)) { // 保存移出下标 removeSet.set(i); removeCount++; } } // 是否被修改过 if (modCount != expectedModCount) { thrownewConcurrentModificationException(); }
// shift surviving elements left over the spaces left by removed elements // 判定是否被修改过 finalbooleananyToRemove= removeCount > 0; if (anyToRemove) { // 新size大小 finalintnewSize= size - removeCount; // 遍历 for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) { // 获取下标 i = removeSet.nextClearBit(i); // 覆盖数据 elementData[j] = elementData[i]; } // 清除多余的数据 for (int k=newSize; k < size; k++) { elementData[k] = null; // Let gc do its work } // 重新设置size this.size = newSize; // 判定修改异常 if (modCount != expectedModCount) { thrownewConcurrentModificationException(); } modCount++; }