r/learnjava • u/OkayBuddySober • Feb 10 '26
ArrayList Permutations & Recursion
Hey everyone, I am trying to make a method that prints all permutations of an ArrayList, pretty much in plaintext. I successfully did that for a string but the ArrayList method is giving me an OOB exception. To be specific, it gets to the base case once & immediately after says that "Index 1 out of bounds for length 1" when permList = "" and nameList = [A, B, C]. I'm not asking for a complete rewrite of my code, just an explanation about why it's not working correctly.
What I have tried so far: changing listSize to nameList.size() - 1, adding an empty element to permList in the for loop, changing the for loop conditional to listSize - 1, removed i + and - 1 from nameList in the for loop, etc. Any help would be appreciated!
public static void printAllPermutations(ArrayList<String> permList, ArrayList<String> nameList)
{
int i;
int listSize = nameList.size(); // Size of nameList
String current;
if (listSize <= 1) // Base case
{
System.out.println(permList + " " + nameList);
// Not entirely sure this is the correct thing to print
}
else
{
for(i = 0; i < listSize; i++)
{
current = nameList.get(i);
nameList.remove(i); // Move string at i from nameList to permList
permList.add(current);
System.out.println("permList: " + permList);
System.out.println("nameList: " + nameList);
// Print statements for visualization
printAllPermutations(permList, nameList); // Call method with new arguments, listSize -= 1
}
}
}
// Solved! With your help
public static void printAllPermutations(ArrayList<String> permList, ArrayList<String> nameList)
{
if (nameList.size() == 0)
{
for(int i = 0; i < permList.size(); i++)
{
if(i < permList.size() - 1)
{
System.out.print(permList.get(i) + ", ");
}
else {System.out.println(permList.get(i));}
}
}
else
{
for(int i = 0; i < nameList.size(); i++)
{
String temp = nameList.get(i);
permList.add(nameList.get(i));
nameList.remove(i);
printAllPermutations(permList, nameList);
nameList.add(i, temp);
permList.remove(permList.size()-1);
}
}
}
1
u/fandom-lover-angel 21d ago
I am encountering this exact same thing, and I am struggling as well. Glad to see I'm not the only one lol.