AbstractCollection superclass location and Overview



AbstractCollection, AbstractSet, AbstractList, AbstractSequentialList AbstractCollection, AbstractSet, abstractBstractList AbstractCollection, AbstractSet, AbbstractList AbstractCollection, AbstractSet, AbbstractList Because the superclass cannot know about the data structure stored, it can only implement publicly known methods. AbstractSequentialList extends AbstractList from the AbstractList class

A basic List interface implementation provides the minimal interface implementation needed to implement sequential access data storage structures.

AbstractCollection superclass AbstractSet, AbstractList, AbstractSequentialList AbstractCollection superclass AbstractSet, AbstractList, AbstractSequentialList AbstractCollection superclass AbstractSet, AbstractList, AbstractSequentialList

AbstractCollection source code

AbstractCollection is an implementation class for a Collection that implements some methods of a Collection and leaves some methods for subclasses to implement.

Methods and descriptions not implemented:

// Query Operations /** * Returns an iterator over the elements contained in this collection. * * @return an iterator over the elements contained in this collection */ public abstract Iterator<E> iterator(); // the iterator method public abstract int size(); // Set size (number of elements in set)Copy the code

Implement a method that does not write and cannot be used:

    /**
     * {@inheritDoc}
     *
     * <p>This implementation always throws an
     * <tt>UnsupportedOperationException</tt>.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     * @throws IllegalArgumentException      {@inheritDoc}
     * @throws IllegalStateException         {@inheritDoc}
     */
    public boolean add(E e) {
        throw new UnsupportedOperationException();
    }
Copy the code

Methods that call iterator(), size(), add() cannot be used in an AbstractCollection superclass.

Implementation method and description:

1. Method isEmpty()

/** * {@inheritdoc} ** <p>This implementation returns <tt>size() == 0</tt>. */ public Boolean isEmpty() return size() == 0; // Select count ();Copy the code

2. Set lookup element contains(Object O)

(1) If the argument is null, find the element whose value is null, return true if it exists, false otherwise. * (2) If the argument is not null, equals equals, true if it exists, false otherwise. * note: */ public Boolean contains(Object o) {Iterator<E> it = Iterator (); If (o==null) {// The element to be found is null while (it.hasnext ()) // loop over the set, if null, break the loop, Return true if (it.next()==null) return true; } else {// The element to be found is not null while (it.hasnext ()) // the equals method is used to check whether the set is equal. } return false; // Return false}Copy the code

ToArray () (Note: The number of elements in the set is larger or smaller than expected because of concurrent modification)

/** * function: convert a collection element to an array of type Object (The number of elements in the collection is larger or smaller than expected because the method allows concurrent modification.) * (1) Create an array of the size of the number of elements in the collection * (2) iterate through the collection, copying the elements from the current collection into the array * (3) If the collection has fewer elements than expected, Array.copyof () copies the elements of the array to the new array and returns the new array * (4) If the array has more elements than expected, finishToArray generates the new array and returns the new array. Public Object[] toArray() {// Estimate size of array; be prepared to see more or fewer elements Object[] r = new Object[size()]; Iterator<E> it = Iterator (); // get iterator for (int I = 0; i < r.length; I++) {// iterate over the collection, copy the elements of the array into the new array if the collection is smaller than expected, and return the new array if (! it.hasNext()) // fewer elements than expected return Arrays.copyOf(r, i); r[i] = it.next(); } return it.hasNext() ? finishToArray(r, it) : r; If the collection has more elements than expected, call finishToArray to generate a new array and return the new array, otherwise return the array created in (1)}Copy the code

ToArray (T[] a);

/** * returns an array of the specified type with a generic constraint: * (1) If the length of the array passed in is greater than or equal to the length of the collection, the elements of the current collection are copied into the array passed in. * (2) If the length of the array passed in is less than the size of the collection, The effect of this annotation is to give the compiler an instruction to remain silent on certain warnings inside the annotated code element. public <T> T[] toArray(T[] a) { // Estimate size of array; be prepared to see more or fewer elements int size = size(); T[] r = a.length >= size? A: // Compare the size of parameter A with the size of the set. If parameter A is large, use array A; (T[]) java.lang.reflect.array.newinstance (a.getClass().getComponentType(), size); Iterator<E> it = Iterator (); Iterator<E> it = Iterator (); // get iterator for (int I = 0; i < r.length; I++) {// if (! It.hasnext ()) {// If (a == r) {// If the array is an array of parameters, set the rest of the values to null r[I] = null; // null-terminate} else if (a.length < I) {// If array length is less than set length, Array.copyof (r, I); return array.copyof (r, I); System.arraycopy(r, 0, a, 0, I); if (a.length > i) { a[i] = null; } } return a; } r[i] = (T)it.next(); // More elements than expected to return it.hasnext ()? finishToArray(r, it) : r; (1) Create a longer array, and copy the contents of the original array into the new array * (2) Expand the array size: Cap + cap/2 +1 * (3) Before capacity expansion, check whether the array length overflows * note: Here the iterator is passed from the upper method (toArray), and the iterator is partially executed, */ @suppressWarnings ("unchecked") private static <T> T[] finishToArray(T[] r, Iterator<? > it) { int i = r.length; while (it.hasNext()) { int cap = r.length; if (i == cap) { int newCap = cap + (cap >> 1) + 1; // overflow-conscious code if (newCap - MAX_ARRAY_SIZE > 0) newCap = hugeCapacity(cap + 1); r = Arrays.copyOf(r, newCap); } r[i++] = (T)it.next(); } // trim if overallocated return (i == r.length) ? r : Arrays.copyOf(r, i); } /** * check whether the array capacity overflow, */ private static int hugeCapacity(int minCapacity) {if (minCapacity < 0) // Overflow throw new OutOfMemoryError ("Required array size too large"); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; }Copy the code

Remove (Object o)

Implementation: * (1) If the argument is null, the first element with a value of NULL is found and deleted, returning true, if there is no null element, returning false. * (2) If the argument is not null, the equals method finds the first element equal to the argument and deletes it, returning true, or false if not found. */ public boolean remove(Object o) { Iterator<E> it = iterator(); if (o==null) { while (it.hasNext()) { if (it.next()==null) { it.remove(); return true; } } } else { while (it.hasNext()) { if (o.equals(it.next())) { it.remove(); return true; } } } return false; }Copy the code

6. Check whether containsAll(Collection<? > c)

/** * implements: */ public Boolean containsAll(Collection<? > c) { for (Object e : c) if (! contains(e)) return false; return true; }Copy the code

7. Add a Collection element addAll(Collection<? extends E> c)

/** * public Boolean addAll(Collection<? extends E> c) { boolean modified = false; for (E e : c) if (add(e)) modified = true; return modified; }Copy the code

RemoveAll (Collection<? > c)

* (1) Check whether the parameter set is empty, if it is empty, throw an exception; Gets the iterator * (2) to traverse the collection, removing * if the current element is in the collection. Public Boolean removeAll(Collection<? > c) { Objects.requireNonNull(c); boolean modified = false; Iterator<? > it = iterator(); while (it.hasNext()) { if (c.contains(it.next())) { it.remove(); modified = true; } } return modified; }Copy the code

RetainAll (Collection<? > c)

* (1) Get the iterator of the current set to traverse * (2) Remove the element from the current set if it is not in the parameter set. Note: Return false if the current collection is a subset of the arguments collection, or true otherwise. */ public boolean retainAll(Collection<? > c) { Objects.requireNonNull(c); boolean modified = false; Iterator<E> it = iterator(); while (it.hasNext()) { if (! c.contains(it.next())) { it.remove(); modified = true; } } return modified; }Copy the code

10. Delete all elements from set clear()

*/ public void clear() {Iterator<E> it = Iterator (); while (it.hasNext()) { it.next(); it.remove(); }}Copy the code

11. The toString method is critical. The implementation plays a key role in the output of the collection we use

Implementation: * (1) // Convert all data in a collection to a string, using the thread-safe and efficient StringBuilder() class to concatenate. */ 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(' '); }}Copy the code

Third, summary

AbstractCollection superclass, as the first implementation class of the top-level interface of collection, implements all classes with similar functions (operations independent of storage structure). On the one hand, it alleviates the overwriting burden (technical term: extracting common methods to implement such things).

Why are iterator(), size(), and add() not implemented?

1. Because there are many ways to implement ADD, which data structure (linked list, array, Map (array + linked list)) cannot be determined as the subclass, so we cannot implement it explicitly. Even if we implement it indirectly in some way, it is too redundant and unnecessary.

2. The reason why it is not specified as an abstract method is that if a subclass does not want to use Add, it is a collection of deletions, changes and checks. Isn’t it paradoxical that we don’t have to implement it.