I have created an ArrayList of ArrayList in java. And iam storing values in them as follows :
import java.util.ArrayList;
class Test {
public static void main(String args[]) {
ArrayList<ArrayList<Integer>> connections = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> currentConnects = new ArrayList<>();
currentConnects.add(7);
currentConnects.add(4);
connections.add(currentConnects);
currentConnects.clear();
currentConnects.add(10);
currentConnects.add(15);
connections.add(currentConnects);
System.out.println(connections);
}
}
I am expecting the output to be :
[[7, 4], [10, 15]]
but the output is :
[[10, 15], [10, 15]]
How can i achieve my expected output without using any other extra variables?
You're actually referencing the same object twice in your connections
object, hence the result you have.
Instead of currentConnects.clear();
try currentConnects = new ArrayList<>();
You need to remove currentConnects.clear(); and create a new ArrayList Object.Your ArrayList objects are pointing to the same Object in heap.The ArrayList<ArrayList<Integer>>
contains same reference of ArrayList twice
import java.util.ArrayList;
class Test {
public static void main(String args[]) {
ArrayList<ArrayList<Integer>> connections = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> currentConnects = new ArrayList<>();
currentConnects.add(7);
currentConnects.add(4);
connections.add(currentConnects);
currentConnects = new ArrayList<>();
currentConnects.add(10);
currentConnects.add(15);
connections.add(currentConnects);
System.out.println(connections);
}
}
You have to create new array lists everytime.
When you do:
connections.add(currentConnects);
currentConnects.clear();
You first add a reference of currentConnects, and then clear the content of currentConnects, you are not creating a new arraylist. Instead do:
ArrayList<Integer> currentConnects = new ArrayList<>();
currentConnects.add(7);
currentConnects.add(4);
connections.add(currentConnects);
currentConnects = new ArrayList<>();
currentConnects.add(10);
currentConnects.add(15);
connections.add(currentConnects);
When you call connections.add(currentConnects);
, since connections
is of type ArrayList<ArrayList<Integer>>
, you're actually adding a reference to entire ArrayList connections, NOT just the integers in the ArrayList itself.
So because you call connections.add(currentConnects);
twice, there are two references to connections
ArrayList, which is why the integers held in connections
are printed out twice.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.