Java.util.Collection at the lowest cost?

I am calling a method in another API that accepts java.util.Collection objects. I looked at the method and immediately copied everything in the collection to a new ArrayList before doing my task.

This made me wonder: what is the absolute lowest Java utility collection that I can use to quickly assemble parameters for this method?

+8
java collections overhead
source share
3 answers

It depends on how it copies the elements, but if it creates an ArrayList -copy like this

 new ArrayList<Something>(inputCollection); 

or if he does

 someCopy.addAll(inputCollection); 

then it will go through inputCollection.toArray() , which is probably best implemented by ArrayList .

+6
source share

It depends on your source data.

If your source data is already an array and the array will not be used by others, the fastest way is to have a thin shell:

 final Object[] source = ... Collection colllection = new AbstractCollection(){ public Object[] toArray(){ return source; } // other methods don't matter } 
0
source share

If you are talking about the amount of memory, look at this table in memory-measurer . Arrays$ArrayList missing, but may be a good alternative to ArrayList ( Arrays.asList(...) ).

0
source share

All Articles