Using java Collections to copy array list
I have seen lot’s of people using Collections.copy and most of times you see this error on console
Exception in thread "main" java.lang.IndexOutOfBoundsException: Source does not fit in dest.
Normally we use following code to copy an array-list
ArrayList<String> items = new ArrayList<String>(); items.add("item 1"); items.add("item 2"); items.add("item 6"); ArrayList<String> items2= new ArrayList<String>(items.size()); Collections.copy(items2,items);
Only problem in the above code is that for list items2 we are assuming that it has same capacity as list items. If you see the code carefully, it is only setting up initial capacity not size and Collections api check for size instead of capacity of list and it result to exception.
IMO there should be an improvement in collection api to copy items, based on capacity, instead of size. See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6350752 .
Solution
You can use any of following option to copy a list
ArrayList<String> items2= new ArrayList<String>(items);
ArrayList<String> items2 = (ArrayList<String>)items.clone();
References
http://java.sun.com/javase/6/docs/api/java/util/Collections.html#copy(java.util.List,%20java.util.List)
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6350752