Reputation: 5680
I want to convert a set to a list. Which method should I prefer (I dont care if it's immutable or not):
version 1:
return List.of(myHashSet().toArray());
or version 2:
return new ArrayList<Strategy>(myHashSet());
Are there any other differences besides that version 1 is immutable? For example, List.of
is more space efficient in compare to ArrayList.
Upvotes: 1
Views: 467
Reputation: 338634
The only differences I see between your 1 and 2 are:
List.of
produces a shallowly immutable list. You cannot add or remove items from the list. Of course, the state within each object contained in the list would still be mutable if already so. Your # 1 results in an immutable list while the ArrayList
of # 2 is mutable.List
. With # 1, you neither know nor control the concrete class used behind the scenes when calling List.of
. The List.of
feature is free to use any class that implements List
interface, possibly even a class not publicly available with the Java Collections Framework. The List.of
feature might even be smart about choosing an optimized class appropriate to your particular collected objects. You said:
List.of is more space efficient in compare to ArrayList.
You cannot make that claim, if you mean usage of memory (RAM). As discussed above, you neither know nor control the choice of class used to implement List
interface when calling List.of
. The class used might vary depending on your data, and might vary by version of Java used at runtime.
As for memory used by the call to toArray
, an array of objects is really just an array of references (pointers). Creating that array takes little memory and is fast. Object references are likely to be a value of four or eight octets (depending on your JVM being 32-bit or 64-bit), though not specified by Java. In creating the array, it is not as if the content of your element objects are being duplicated. So for most common apps the brief creation and disposal of that array would be insignificant.
And, as commented by Kuhn, Java 10 saw the arrival of a new factory method List.copyOf
that takes a Collection
. So no need to call toArray
.
List<Strategy> myStrategyList = List.copyOf( myStrategySet ) ;
Conclusion:
List.copyOf
. List
, use that particular class.Upvotes: 2