Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the logic behind clear() in ArrayList

Tags:

java

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;

    }
like image 733
user1896796 Avatar asked Sep 12 '19 09:09

user1896796


1 Answers

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);
    }
}
like image 199
Eran Avatar answered Sep 28 '22 02:09

Eran