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

科技回声

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

GitHubTwitter

首页

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

资源链接

HackerNews API原版 HackerNewsNext.js

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

Java collections framework for newbies

17 点作者 mainguy超过 13 年前

2 条评论

scorchin超过 13 年前
As of Java 1.5, generics were added. Before generics you had to cast every object you read from a collection. If someone accidentally inserted an object of the wrong type — possible in the OP's example code — casts could fail at runtime.<p>With generics, you tell the compiler what types of objects are permitted in each collection. The compiler inserts casts for you automatically and tells you at <i>compile time</i> if you try to insert an object of the wrong type. This results in programs that are both safer and clearer. So please use generics when using the collections framework.<p>I'm now going to briefly run through the examples provided in OP's post and update them accordingly.<p><pre><code> List&#60;String&#62; myList = new ArrayList&#60;String&#62;(); myList.add("Second Thing"); myList.add("Second Thing"); myList.add("First Thing"); </code></pre> Note that I've used the interface form of <i>List</i> over a specialised type. This is so that any caller of a method which returns a collection can use the interface provided and they don't need to worry about the specific data structures you've used. This also means that you can update the underlying data structure without having to update any calling code. E.g. changing the above case from <i>ArrayList</i> to <i>LinkedList</i>.<p><pre><code> Set&#60;String&#62; mySet = new HashSet&#60;String&#62;(); mySet.add("Second Thing"); mySet.add("Second Thing"); mySet.add("First Thing"); </code></pre> It is worth noting that Hashtable was <i>not originally</i> part of the Collections framework. It was retrofitted to conform to the Map interface in 1.2. You should instead use HashMap, which is the non-synchronized (sic) version of Hashtable. Although you can just as easily use Hashtable, the below example is just me being a little OCD.<p><pre><code> Map&#60;String, String&#62; myMap = new HashMap&#60;String, String&#62;(); myMap.put("a", "Second Thing"); myMap.put("b", "Second Thing"); myMap.put("c", "First Thing"); </code></pre> <i>EDIT</i>: Updated some sections to read clearer.
评论 #3333749 未加载
choffstein超过 13 年前
I am sort of dumb-founded that this is on the front-page of HackerNews. I know this isn't a constructive comment in any way, but this link is to a basic post that is going over the different between a list, a set, and a map?<p>Really?
评论 #3333896 未加载
评论 #3333697 未加载
评论 #3333917 未加载