The pits stepped on using Java’s ArrayList

During normal development, ArrayList is frequently used, but it is easy to step on the pit if you are not careful. Record it here.

1. Use arrays Aslist's pit

Usage scenario @ h_ 301_ 5 @ normal use of arrays Aslist won't have much problem list < integer > testlist = arrays asList(1, 2, 3);

Analysis @ h_ 301_ 5 @ normally, the ArrayList we use is Java Util. Looking at the source code, we can find that the ArrayList returned by aslist is actually an internal class of the arrays class, and this internal class does not override the add method, so an error will be reported. Therefore, the scientific use posture is that after the declaration, do not call the add method to modify the collection. You can modify it in advance and then convert it.

2. Use the sublist of ArrayList

Usage scenario @ h_ 301_ 5@ (1). Modifying the value of the original set will affect the subset list < string > testlist = new ArrayList < > ();

Analysis @ h_ 301_ 5@ check the source code of sublist: it is found that the constructor of sublist class is called: the constructor here does not recreate ArrayList, so modifying the value of the original set or subset will affect each other.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>