Wednesday, January 28, 2009
java Collections.copy behavior is unexpected
Yesterday I was trying to sort a Collection returned by JDO. Of course this is not possible as JDO resultsets are read-only. So I looked up for a java function that will allow me to copy the JDO collection to a new collection, which I would then sort.
The first function that popped up was Collections.copy(Collection dest, Collection src). After I coded up the copy, it crashed with an IndexOutOfBounds exception inside the copy method.
Upon further investigation, I found that the destination Collection has to have a size no less than the source list. This is not what one expects from a copy method. It seems like Sun introduced this function as a convenience in overwriting an existing collection with a different collection. You can read about it here.
Fortunately, if your collection is a List, there is a List.addAll(Collection c) method that would copy a collection to the list.
Subscribe to:
Post Comments (Atom)
1 comment:
But does it do a shallow copy or a deep copy? With the explosion of proxy frameworks like Spring and JPA, this is the big question.
Post a Comment