TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Stop casting to List (Java)

2 点作者 flormmm超过 7 年前

2 条评论

niftich超过 7 年前
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>
haglin超过 7 年前
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.