I am using below program to find the subsequences in an given given list. When I am using clear() , the values in li is also getting cleared. Hence, I am creating a new reference everytime.
I wanted to understand the logic behind this. Am I using it wrong? Or it is the reference that I am adding to my li?
public static int getTheSubseq(List<Integer> AList){
// int[][] subsequences = new int[][];
List<List<Integer>> li = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
for (int i = 0; i < AList.size(); i++){
for(int j =i+1; j < AList.size(); j++){
temp.add(AList.get(i));
temp.add(AList.get(j));
li.add(temp);
temp = new ArrayList<>();
//temp.clear();
}
}
System.out.println(li);
return 1;
}
Regardless of whether or not you are calling temp.clear(), if you add to li multiple times a reference to the same List object, li will contain multiple references to the same List object, which means li.get(0) == li.get(1), li.get(0) == li.get(2), and so on...
Making changes in one of these inner Lists will be reflected in all the other inner Lists, since there's just one List referenced multiple times.
Therefore, assigning a new ArrayList instance to temp in each iteration of your loop (before adding it to li) is the right thing to do.
I'd make a slight change though - create the new inner List just before adding it to the outer List:
for (int i = 0; i < AList.size(); i++){
for(int j =i+1; j < AList.size(); j++){
List<Integer> temp = new ArrayList<>();
temp.add(AList.get(i));
temp.add(AList.get(j));
li.add(temp);
}
}
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