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].
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.
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);
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.
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.
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