Home> Java> JavaBase> body text

Record the pitfalls of Java collection class List

coldplay.xixi
Release: 2020-12-17 17:16:14
forward
3031 people have browsed it

Java basic tutorialColumn introduction Collection class includes two major categories: Map and Collection

Record the pitfalls of Java collection class List

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.

The first pitfall: the List returned by the Arrays.asList method does not support addition and deletion operations

For example, if we execute the following code:

List strings = Arrays.asList("m", "g"); strings.add("h");
Copy after login

will throwjava .lang.UnsupportedOperationExceptionException, 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 enableDebugDafa:

Record the pitfalls of Java collection class List

found that the returnedArrayListis not our commonly usedjava .util.ArrayList, but the inner classjava.util.Arrays.ArrayListofArrays. Enter the methodArrays.asListand the source code is as follows:

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

The method returns the static internal classjava.util.Arrays.ArrayListofArrays, Although this class andjava.util.ArrayListalso 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'saddmethod throwsjava.lang.UnsupportedOperationExceptionexception by default.

Record the pitfalls of Java collection class List

The root cause of this pitfall is that theaddmethod of thestringsreturned by our call is inherited from the abstract parent classaddmethod, and the method of the abstract parent class throws thejava.lang.UnsupportedOperationExceptionexception by default.

The second pitfall is that the new List returned by the Arrays.asList method and the modification of the original parameter group of the method will affect each other

Arrays.asListmethod except the aboveDoes not support adding or deleting elementsIn addition to this pit, there is another pit:

Record the pitfalls of Java collection class List

It can be found from the above code that modifications to the original array will affect The newListwe obtained through theArrays.asListmethod can be found by digging into the source code ofjava.util.Arrays.ArrayList:

private static class ArrayList extends AbstractList implements RandomAccess, java.io.Serializable { private static final long serialVersionUID = -2764017481108945198L; private final E[] a; ArrayList(E[] array) { a = Objects.requireNonNull(array); } ... }
Copy after login

The original array is used directly, so we must pay special attention when we use theListobtained 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 theArrayListconstructor method tonewaList(e.g.List stringList = new ArrayList<>(Arrays.asList(arrays))) or passLists.newArrayListin theGuavalibrary, the newListwill be returned Decoupled from the original array, they will no longer affect each other.

The third pitfall is that if you directly traverse the List collection to delete elements, an error will be reported.

When you directly traverse the collection elements, adding or deleting elements will report an error. For example, if you execute the following code:

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

The above code can be compiled normally, but thejava.util.ConcurrentModificationExceptionexception will be thrown when executed. Looking at the source code, you can find that the deletion element methodremovewill modify the collection structure, and also That is,modCount (the number of actual modifications to thecollection) will be modified. During the loop, the actual number of modifications to the currentListcollectionmodCountwill be compared with the iterator modification. The number ofexpectedModCount, andexpectedModCountis themodCountduring initialization. If the two are not equal, aConcurrentModificationExceptionexception will be reported. There are two main solutions: 1. Use the iterator method ofArrayListto traverse, and then call the methods in it. 2. In JDK 1.8, you can use theremoveIfmethod to perform deletion operations.

Finally, a heart-wrenching question: Call theremovemethod ofArrayListand pass inintbasic type numbers andIntegerAre 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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!