Java basic tutorialColumn introduction Collection class includes two major categories: Map and Collection
Recommendation (free):java basic tutorial
Some high-level programming languages now provide the implementation of various out-of-the-box data structures, such as Java programming The collection framework of the language provides various implementations. The collection class includes two major categories: Map and Collection. The List below Collection is one of the collection classes we often use. Many business codes are inseparable from it. Today Let’s take a look at some pitfalls of List lists.
For example, if we execute the following code:
Liststrings = Arrays.asList("m", "g"); strings.add("h");
will throwjava .lang.UnsupportedOperationException
Exception, what is your OSat this time? Why can't elements be added to the returned ArrayList? Can elements be added properly in the future?
, and then decisively enableDebug
Dafa:
found that the returnedArrayList
is not our commonly usedjava .util.ArrayList
, but the inner classjava.util.Arrays.ArrayList
ofArrays
. Enter the methodArrays.asList
and the source code is as follows:
public staticList asList(T... a) { return new ArrayList<>(a); }
The method returns the static internal classjava.util.Arrays.ArrayList
ofArrays
, Although this class andjava.util.ArrayList
also inherit from the abstract classjava.util.AbstractList
, but through the source code of this class, it is found that it does not have any reference to the abstract parent classAbstractList
'sadd
method throwsjava.lang.UnsupportedOperationException
exception by default.
The root cause of this pitfall is that theadd
method of thestrings
returned by our call is inherited from the abstract parent classadd
method, and the method of the abstract parent class throws thejava.lang.UnsupportedOperationException
exception by default.
Arrays.asList
method except the aboveDoes not support adding or deleting elementsIn addition to this pit, there is another pit:
It can be found from the above code that modifications to the original array will affect The newList
we obtained through theArrays.asList
method can be found by digging into the source code ofjava.util.Arrays.ArrayList
:
private static class ArrayListextends AbstractList implements RandomAccess, java.io.Serializable { private static final long serialVersionUID = -2764017481108945198L; private final E[] a; ArrayList(E[] array) { a = Objects.requireNonNull(array); } ... }
The original array is used directly, so we must pay special attention when we use theList
obtained byArrays.asList
. Because the array is shared, some unexpected bugs may occur when modifying each other. . One of the standard actions is to use it as a parameter of theArrayList
constructor method tonew
aList
(e.g.List
) or passLists.newArrayList
in theGuava
library, the newList
will be returned Decoupled from the original array, they will no longer affect each other.
When you directly traverse the collection elements, adding or deleting elements will report an error. For example, if you execute the following code:
ListstringList = Lists.newArrayList("m", "g", "h"); for (String s : stringList) { if (Arrays.asList("m", "h").contains(s)) { stringList.remove(s); } }
The above code can be compiled normally, but thejava.util.ConcurrentModificationException
exception will be thrown when executed. Looking at the source code, you can find that the deletion element methodremove
will modify the collection structure, and also That is,modCount (the number of actual modifications to the
collection) will be modified. During the loop, the actual number of modifications to the currentList
collectionmodCount
will be compared with the iterator modification. The number ofexpectedModCount
, andexpectedModCount
is themodCount
during initialization. If the two are not equal, aConcurrentModificationException
exception will be reported. There are two main solutions: 1. Use the iterator method ofArrayList
to traverse, and then call the methods in it. 2. In JDK 1.8, you can use theremoveIf
method to perform deletion operations.
Finally, a heart-wrenching question: Call theremove
method ofArrayList
and pass inint
basic type numbers andInteger
Are the execution results of packaging type numbers the same?
The above is the detailed content of Record the pitfalls of Java collection class List. For more information, please follow other related articles on the PHP Chinese website!