I have two ArrayList
s (a1
and a2
) as below:
ArrayList a1 = new ArrayList();
a1.add(8);
a1.add("a1");
ArrayList a2 = new ArrayList();
a2.add(a1); //output : [[8, a1]]
a2.addAll(a1); //output : [[8, a1], 8, a1]
My Questions:
a2.addAll()
method prints the data twice?add
and addAll
? Both the methods return boolean.The addAll() method of java. util. Collections class is used to add all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array. The behavior of this convenience method is identical to that of c.
AddAll is faster than Add Similarly, addAll provides higher operations per second when compared with add . So next time when you are adding something to an array make sure that you pile them and add it using addAll . The addAll is almost twice as fast as the add version.
List addAll() Method in Java with Examples. This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator.
However, there is a major difference between them. The set() method adds a new element at the specified position by replacing the older element at that position. The add() method adds a new element at the specified position by shifting the older element towards the right position.
Why
a2.addAll()
method prints the data twice?
Because the first copy is already there after you called add(a1)
on the previous line.
What is the exact difference between
add()
andaddAll()
? Both the methods returnboolean
.
add
adds a single item, while addAll
adds each item from the collection one by one. In the end, both methods return true
if the collection has been modified. In case of ArrayList
this is trivial, because the collection is always modified, but other collections, such as Set
, may return false
if items being added are already there.
Note: Part of the confusion is that your lists are untyped, so they contain a mixture of objects: a1
mixes strings and numbers, while a2
mixes strings, numbers, and lists. Using a specific generic type for your collection would prevent this confusion by letting you do either add
or addAll
, but not both:
List<String> a1 = new ArrayList<>();
a1.add("8");
a1.add("a1");
List<List<String>> a2 = new ArrayList<>();
a2.add(a1);
a2.addAll(a1); // <<== Does not compile
List<String> a3 = new ArrayList<>();
a3.add(a1); // <<== Does not compile
a3.addAll(a1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With