Hacker News new | past | comments | ask | show | jobs | submit login
Stop casting to List (Java) (paultyma.blogspot.com)
2 points by flormmm on Feb 13, 2018 | hide | past | favorite | 2 comments



The advantage of declaring variables and parameters as List instead of the specific implementation like ArrayList or LinkedList is that generic method calls can accept any List; this becomes most useful when you're writing generic library code, or when in your code you use some of the exotic implementations (like those in Guava or Apache Commons) for some useful purpose, as is often done for immutability, data locality, or code simplification.

Java actually provides a marker interface to distinguish between implementations of lists that support fast random access [1] and those that don't, and library code is encouraged to use this to decide an optimal codepath.

[1] https://docs.oracle.com/javase/8/docs/api/java/util/RandomAc...


If you use LinkedList and ArrayList in an API, you can't pass a list created by the following factory methods:

Collections.emptyList() Collections.singletonList() Collections.unmodifiableList() List.of()

As niftich points out, use the marker interface java.util.RandomAccess, if you want to know if the list allows constant time access.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: