Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add elements of one ArrayList to another ArrayList

Tags:

java

Is it possible to add the elements of one Arraylist to another Arraylist? For example if an Arraylist has elements 3,6,3,8,5 in index 0,1,2,3,4, now I want to add 3,6,3,8,5 to another ArrayList in index 0, is it possible?

ArrayList<String> num = new ArrayList<String>();
 num.add("3");
 num.add("6");
 num.add("3");
 num.add("8");
 num.add("5");
ArrayList<String> result = new ArrayList<String>();
 for (int i = 0; i < num.size(); i++)
 {
        result.addAll(i,num);   
 }

I have tried this but it is not working. what i want is when i try System.out.println(result.get(0)); result must be [3 6 3 8 5].

like image 294
koshish kharel Avatar asked Apr 04 '15 05:04

koshish kharel


People also ask

How do I copy values from one ArrayList to another?

In order to copy elements of ArrayList to another ArrayList, we use the Collections. copy() method. It is used to copy all elements of a collection into another. where src is the source list object and dest is the destination list object.

Can you set an ArrayList equal to another ArrayList?

We can also change one value of one ArrayList and can look for the same in the other one whether it is changed or not. Syntax : ArrayList<Integer> gfg=new ArrayList<>(); ArrayList<Integer> gfg2=new ArrayList<>(gfg);

How do you equate two ArrayLists?

The ArrayList. equals() is the method used for comparing two Array List. It compares the Array lists as, both Array lists should have the same size, and all corresponding pairs of elements in the two Array lists are equal.


1 Answers

I think what you are trying to do is this:

for (int i = 0; i < num.size(); i++) {
    result.add(i, num.get(i)); 
}

Or maybe just this:

result.addAll(num);

What your current code does is you add all of num to result many times ... at successive starting positions. That is ... strange.


UPDATE

What i want is when i try System.out.println(result.get(0)); result must be [3 6 3 8 5].

Ah ... I get it ... you are trying to create a list of strings where the strings are representations of the input lists:

Do this:

for (int i = 0; i < num.size(); i++) {
    result.add(i, num.toString()); 
}

This will give you the output you are asking for.

Another possibility is that you want a list of lists of strings:

ArrayList<ArrayList<String>> result = new ArrayList<>();
for (int i = 0; i < num.size(); i++) {
    result.add(i, num); 
}

That will also give you the output you are asking for ... though for a different reason.

like image 72
Stephen C Avatar answered Oct 08 '22 12:10

Stephen C