Ali Java development manual analysis:

  • 6.1[Mandatory] Handling of hashCode and equals

  • 6.5 [Mandatory] The subList result of ArrayList cannot be forcibly converted to ArrayList; otherwise, a ClassCastException will be thrown

  • 6.8 “mandatory” in the subList scenario, highly pay attention to the add or remove elements to the parent collection, all can lead to child list traversal ConcurrentModificationException, add, delete

  • 6.9 [mandatory] to convert collection toArray, the toArray(T[] array) of the collection must be used, and an empty array of the same type and length 0 is passed in.

  • When using arrays.aslist () to convert Arrays to collections, you can’t use its add/remove methods to modify collections

  • 6.14 [Mandatory] Do not remove/add elements in foreach loops. Use Iterator for remove elements

  • 6.15 [Mandatory] In JDK7 or later, the implementation of the Comparator class must satisfy the following three conditions; otherwise, Arrays. Sort, collections. sort will throw IllegalArgumentException.

  • In JDK7 and above, use the diamond syntax or skip all generic definitions. Note: Diamond generics, known as diamond, use <> directly to refer to the previously specified type.

  • 6.18 [Recommendation] Use entrySet to traverse the Map class set KV instead of keySet.


“Forced” to use tools Arrays. AsList () converts an array into a collection, you can’t use the modify the related methods of collection, it’s the add/remove/clear method will throw an UnsupportedOperationException anomalies.

The return object of asList is an Array inner class that doesn’t implement collection modification methods. AsList is an adaptor mode, just an interface, and the data in the background is still an array.

Abnormal demo:

public static void main(String[] args) {
        String[] str = new String[] { "A"."B" };
        List list = Arrays.asList(str);
        // The first case:
         list.add("C");
    }
Copy the code

Output log:

AsList (STR) returns an internal class of Arrays that is not supplied externally.


public class Arrays {
	public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }

    / * * *@serial include
     */
    private static class ArrayList<E> extends AbstractList<E>
        implements RandomAccess.java.io.Serializable
    {
        private static final long serialVersionUID = -2764017481108945198L;
        private final E[] a;

        ArrayList(E[] array) {
            a = Objects.requireNonNull(array);
        }

        @Override
        public int size(a) {
            return a.length;
        }

        @Override
        public Object[] toArray() {
            return a.clone();
        }

        @Override
        @SuppressWarnings("unchecked")
        public <T> T[] toArray(T[] a) {
            int size = size();
            if (a.length < size)
                return Arrays.copyOf(this.a, size,
                                     (Class<? extends T[]>) a.getClass());
            System.arraycopy(this.a, 0, a, 0, size);
            if (a.length > size)
                a[size] = null;
            return a;
        }

        @Override
        public E get(int index) {
            return a[index];
        }

        @Override
        public E set(int index, E element) {
            E oldValue = a[index];
            a[index] = element;
            return oldValue;
        }

        @Override
        public int indexOf(Object o) {
            E[] a = this.a;
            if (o == null) {
                for (int i = 0; i < a.length; i++)
                    if (a[i] == null)
                        return i;
            } else {
                for (int i = 0; i < a.length; i++)
                    if (o.equals(a[i]))
                        return i;
            }
            return -1;
        }

        @Override
        public boolean contains(Object o) {
            returnindexOf(o) ! = -1;
        }

        @Override
        public Spliterator<E> spliterator(a) {
            return Spliterators.spliterator(a, Spliterator.ORDERED);
        }

        @Override
        public void forEach(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            for(E e : a) { action.accept(e); }}@Override
        public void replaceAll(UnaryOperator<E> operator) {
            Objects.requireNonNull(operator);
            E[] a = this.a;
            for (int i = 0; i < a.length; i++) { a[i] = operator.apply(a[i]); }}@Override
        public void sort(Comparator<? super E> c) { Arrays.sort(a, c); }}}Copy the code

This ArrayList doesn’tadd(e)Method implementation:

AbstractList

class ArrayList

extends AbstractList



public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
	
    public boolean add(E e) {
        add(size(), e);
        return true;
    }
	
   public void add(int index, E element) {
        throw newUnsupportedOperationException(); }}Copy the code

ArrayList itself doesn’t support add(e).

As you can see, this class stores Array object A, and some of the operations in it operate on object A. Public E set(int index, E element):

 @Override
        public E set(int index, E element) {
            E oldValue = a[index];
            a[index] = element;
            return oldValue;
        }
Copy the code

Therefore, modification of the returned object of arrays.aslist (a) will result in modification of the original Array data synchronization. Modifying the array also causes the returned object to change:

Test the demo:

    public static void main(String[] args) {
        String[] str = new String[] { "A"."B" };
        List list = Arrays.asList(str);
       
       list.set(0."C");
        System.out.println("String[] str :");
        for (String s : str) {
            System.out.println(s);
        }
        System.out.println("Arrays.ArrayList :");
        str[1] ="D";
        for(Object o : list) { System.out.println(o); }}Copy the code

Log output:

String[] str :
C
B
Arrays.ArrayList  :
C
D

Process finished with exit code 0

Copy the code