The correct solution depends on whether you want to ensure that the elements you put into targetList
really are instances of ObjectType
(or a subtype).
If you don't care, one of the solutions with an unsafe typecast will do. Unless you need to copy, @Toms solution is better. (You might need to copy if getResults()
returns a linked list and your algorithm needs to use targetList.get(int)
a lot.) But beware that you might get an unexpected ClassCastException
later on if your assumptions are incorrect.
If you need to be sure that there are no elements of the wrong type, then you have to use an iterator-based solution unless you know what kind of List
type that getResults()
gives you. (If you can cast the result of getResults()
to ArrayList
, then indexing using get(int)
should be faster than using an Iterator
. On the other hand, if the result is a LinkedList
, then using get(int)
to copy the list is O(N**2)
!!)
How about this?
final List<?> resultList = problemSolver.getResults();
List<ObjectType> targetList;
if (resultList == null || resultList.isEmpty()) {
targetList = Collections.empyList();
} else {
int len = resultList.size();
// it is important to preallocate the ArrayList with the
// right size ... to conserve space and avoid copy on realloc
// of the list's private backing array.
targetList = new ArrayList<ObjectType>(len);
if (resultList instanceof ArrayList) {
// Copy using indexing - O(N) for ArrayLists
ArrayList<?> arrayList = (ArrayList) resultList;
for (int i = 0; i < len; i++) {
targetList.add((ObjectType) (arrayList.get(i)));
}
} else {
// Copy using iterator - O(N) for all sane List implementations,
// but with a larger C than the best case for indexing.
for (Object obj : resultList) {
targetList.add((ObjectType) obj);
}
}
}