Java.lang.IndexOutOfBoundsException: source does not fit in dest

In 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 get an error message:

 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?

+64
java collections arraylist indexoutofboundsexception
May 27 '11 at 3:47
source share
3 answers

Capacity is not equal to size. The size parameter you pass in just allocates enough memory for the size. It does not actually define elements. This is actually a stupid requirement of Collections.copy , but it is nonetheless.

Key part of Collections.copy JavaDocs :

The mailing list should be no less than the list of sources. If it is longer, the remaining items in the mailing list are not affected.

You just have to pass the List constructor to the ArrayList constructor to copy all the List to avoid the problem at all.

+78
May 27 '11 at 3:52
source share

This is a very good question, and it is almost certainly due to the fact that setting the collection capacity does not necessarily highlight the underlying objects, but why do you do it this way when you can simply:

 ArrayList <Integer> numbersCopy = new ArrayList<Integer>(numbers); 
+19
May 27 '11 at 3:51
source share

The ArrayList(Collection<? extends E> c) constructor ArrayList(Collection<? extends E> c) will copy all the elements from c to the newly created instance by copying numbers into numbersCopy . This is the same as numbersCopy.addAll(numbers) that you really need.

It makes sense that Collection.copy requires the dest array to be large enough to hold all the elements from the source array. A similar analogy is the C memcpy function, etc.

+4
May 27 '11 at 4:03 a.m.
source share



All Articles