On the following code:
static void findSubsets (ArrayList<Integer> numbers, int amount, int index)
{
ArrayList <Integer> numbersCopy = new ArrayList<Integer>(numbers.size());
Collections.copy(numbersCopy, numbers);
}
I’m getting the error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Source does not fit in dest
at java.util.Collections.copy(Collections.java:548)
at backtracking2.Main.findSubsets(Main.java:61)
Why?
Capacity does not equal size. The size parameter that you are passing in simply allocates enough memory for the size. It does not actually define elements. It’s actually kind of a silly requirement of
Collections.copy, but it is one nonetheless.The key part from the
Collections.copyJavaDocs:You should just pass the
Listto theArrayList‘s constructor to copy all of theListto avoid the issue altogether.