Some high-level programming languages now provide implementations of various data structures out of the box. For example, the Java programming language’s Collection framework provides implementations of the Collection classes including Map and Collection. The List below Collection is one of the Collection classes we often use, and many business codes cannot do without it. Today, we will take a look at some pits in the List.

The first one is that the arrays. asList method doesn’t add or delete lists

For example, we execute the following code:

List<String> strings = Arrays.asList("m", "g");
strings.add("h");
Copy the code

Throws the Java. Lang. UnsupportedOperationException abnormalities, OS what inside of you right now? Why can’t you add elements to the returned ArrayList? And then enable Debug:

Found back the ArrayList is not our commonly used Java. Util. ArrayList, but Java Arrays of inner class. The util. Arrays. The ArrayList. Arrays.asList = arrays. asList

public static <T> List<T> asList(T... a) {
    return new ArrayList<>(a);
}
Copy the code

Method returns a Arrays of a static inner class. Java util. Arrays. The ArrayList, although the class and Java. Util. The ArrayList is inherited from an abstract class. Java util. AbstractList, But through the class source found it did not add to the abstract parent class AbstractList method. The default is to throw out the Java lang. UnsupportedOperationException anomalies.

The root cause of the pit is what we call returns the strings of the add method is inherited from the add method of abstract parent class, and the abstraction of the parent class method is thrown by default Java lang. UnsupportedOperationException this exception. Search the programmer Maidong public account, reply “888”, send you a 2020 latest Java interview questions manual. PDF

The second pitfall is that the new List returned by the arrays.aslist method interacts with the original input group modification of that method

Arrays.asList does not support adding or deleting elements:

From the above code can be found that the changes will affect our original array by Arrays. The asList method to obtain the new List, in-depth Java. Util. Arrays. The ArrayList source code:

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); }... }Copy the code

It can be found that the original Arrays are used directly, so we should pay special attention to the List obtained by using arrays.aslist, because the shared Arrays may cause some unexpected bugs when modifying each other. One of the standard postures is to simply create a new List as an argument to the ArrayList constructor (e.g. List stringList = new ArrayList<>(arrays.aslist (Arrays)) or pass The Lists. NewArrayList in the Guava library decouples the returned new List from the original array and no longer affects each other. Search the programmer Maidong public account, reply “888”, send you a 2020 latest Java interview questions manual. PDF

Third, iterating through the List collection to delete elements will cause an error

An error is reported when adding or deleting elements while traversing the collection directly, such as the following code:

List<String> stringList = Lists.newArrayList("m", "g", "h"); for (String s : stringList) { if (Arrays.asList("m", "h").contains(s)) { stringList.remove(s); }}Copy the code

The above code can be compiled by normal, but the execution thrown when the Java. Util. ConcurrentModificationException abnormalities, view its source code can be found, remove removing elements method can make the collection structure modification, The modCount (the actual number of times the set is modified) is modified, and during the loop, the actual number of times the set of the current List is modified, modCount, is compared with the number of times the iterator is modified, And expectedModCount modCount is initialized, the two are not equal, will quote ConcurrentModificationException anomalies. There are two main ways to solve this problem: 1. Use the iterator of an ArrayList to traverse and then call its methods. 2. In JDK 1.8+, you can use the removeIf method to delete files.

If the ArrayList remove method is passed a primitive int and a wrapper Integer, the result is the same.

The last

Thank you for reading here, the article is inadequate, welcome to point out; If you think it’s good, give me a thumbs up.

Also welcome to pay attention to my public number: Java programmers gathering place, Maidong will share Java related technical articles or industry information every day, welcome to pay attention to and forward the article!