Home > database >  List of List not retaining the contents
List of List not retaining the contents

Time:02-13

so I have a recursive program where I am trying to generate all the permutations of a String. I intend to store the permutations in a list of list called ans.

Every single current permutation is stored in the container list which is used to populate the ans list. I am suspecting , since list is a reference type so maybe I am loosing the values in ans list because the container list is getting manipulated? Am I an idiot



import java.util.*;
public class practice_3 {
   static String str="abc";
   static List<List<Character>> ans=new ArrayList<List<Character>>();

   
public static void permString(ArrayList container )
{
    if(container.size()==str.length())
        {System.out.println(container);
        
        ans.add(container);
        return;
        }
    
    for(int i=0;i<str.length();i  )
    {
        if(!container.contains(str.charAt(i)))
        {
            container.add(str.charAt(i));
            permString(container);
            container.remove(container.size()-1);
            
        }
            
    }
    
}
public static void main(String[] args) {
    
    ArrayList<Character> container=new ArrayList<>();
    
    
    permString(container);
    System.out.println(ans);
    System.out.println("container end=" container);
    
    
}

}

CodePudding user response:

You are correct, as container was passed by reference the changes made in container from point to point reflects within ans (Collection of Collection) as well.

To avoid this, you need to clone / create a new copy of the container at the time of storing into the ans collection. This can be easily achieved by following.

ans.add(new ArrayList<Character>(container));
  • Related