I'm addicted to it.
When dealing with lists in Java, I think I often use ArrayList as new.
hoge.java
List<String> list = new ArrayList<>();
When I asked Google teacher when I wanted to reuse the ArrayList,
I think that two ways are recommended. And I don't mention the difference between the two, and I think that Qiita's article will be a hit, saying "The execution speed is different" if you force it.
However, in reality, there are differences not only in speed but also in behavior.
Suppose you want to create a two-dimensional list by extracting two elements from the one-dimensional list.
The sample code is shown below. First of all, it is from the case of new.
sample.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TestArraylist {
public static void main(String args[]) {
//2D list for output
List<ArrayList<String>> sampleLists = new ArrayList<>();
//Temporary list for adding elements to sampleLists
ArrayList<String> listA = new ArrayList<>();
//Suitable sample
List<String> listB = Arrays.asList("AA", "BB", "CC", "DD", "EE", "FF");
//Create a list with 2 elements and add it to sampleLists
for (int i = 0; i < listB.size(); i++) {
if (i % 2 == 0) {
listA.add(listB.get(i));
continue;
}
sampleLists.add(listA);
listA.add(listB.get(i));
//Confirmation before new
System.out.println(sampleLists);
//New temporary list
listA = new ArrayList<>();
//Confirmation after new
System.out.println(sampleLists);
}
}
}
When you do this ...
[[AA, BB]]
[[AA, BB]]
[[AA, BB], [CC, DD]]
[[AA, BB], [CC, DD]]
[[AA, BB], [CC, DD], [EE, FF]]
[[AA, BB], [CC, DD], [EE, FF]]
You can see that the list is exactly what you want.
On the other hand, suppose you use the clear method instead of new. The output when listA = new ArrayList <> ();
in the above sample is rewritten to the code listA.clear ();
using the clear method is ...
[[AA, BB]]
[[]]
[[CC, DD], [CC, DD]]
[[], []]
[[EE, FF], [EE, FF], [EE, FF]]
[[], [], []]
In this way, ** the element that should have been added will be a list of element 0 every time the clear method is called, and the newly added element will be added to all the lists until the next call to the clear method. Masu **.
When I try to google, there are many pages that say which one can be used to erase the elements of the array, so I'm not careful, but in reality it behaves differently as described above, so be careful.
Recommended Posts