TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Stop casting to List (Java)

2 pointsby flormmmover 7 years ago

2 comments

niftichover 7 years ago
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&#x27;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.<p>Java actually provides a marker interface to distinguish between implementations of lists that support fast random access [1] and those that don&#x27;t, and library code is encouraged to use this to decide an optimal codepath.<p>[1] <a href="https:&#x2F;&#x2F;docs.oracle.com&#x2F;javase&#x2F;8&#x2F;docs&#x2F;api&#x2F;java&#x2F;util&#x2F;RandomAccess.html" rel="nofollow">https:&#x2F;&#x2F;docs.oracle.com&#x2F;javase&#x2F;8&#x2F;docs&#x2F;api&#x2F;java&#x2F;util&#x2F;RandomAc...</a>
haglinover 7 years ago
If you use LinkedList and ArrayList in an API, you can&#x27;t pass a list created by the following factory methods:<p>Collections.emptyList() Collections.singletonList() Collections.unmodifiableList() List.of()<p>As niftich points out, use the marker interface java.util.RandomAccess, if you want to know if the list allows constant time access.