Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use addall() method of collections?

i need to use it to merge two ordered list of objects.

like image 512
bhavna raghuvanshi Avatar asked Jun 16 '10 10:06

bhavna raghuvanshi


People also ask

How do I use addAll collection?

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.

What is the use of addAll method in Java?

The main function of the addAll() method in Java is to add elements into a Java collection. There are two addAll() methods in Java: The static method in the Collections class. The instance method in the Collection interface.

What is difference between ADD and addAll?

add method is used in List when you wish to add ONE element to the end of the list. . addall method is used when you wish to add contents of an already existing List to a List.

Why does addAll return Boolean?

The addAll() method returns a Boolean value true, if the queue has changed as a result of this call else it returns false.


1 Answers

From the API:

addAll(Collection<? extends E> c): Adds all of the elements in the specified collection to this collection (optional operation).

Here's an example using List, which is an ordered collection:

    List<Integer> nums1 = Arrays.asList(1,2,-1);
    List<Integer> nums2 = Arrays.asList(4,5,6);

    List<Integer> allNums = new ArrayList<Integer>();
    allNums.addAll(nums1);
    allNums.addAll(nums2);
    System.out.println(allNums);
    // prints "[1, 2, -1, 4, 5, 6]"

On int[] vs Integer[]

While int is autoboxable to Integer, an int[] is NOT "autoboxable" to Integer[].

Thus, you get the following behaviors:

    List<Integer> nums = Arrays.asList(1,2,3);
    int[] arr = { 1, 2, 3 };
    List<int[]> arrs = Arrays.asList(arr);

Related questions

  • Arrays.asList() not working as it should?
like image 169
polygenelubricants Avatar answered Oct 05 '22 23:10

polygenelubricants