[英]Why does the Java compiler not like primitive int as type for values in HashMap?
編譯器抱怨這段代碼:
HashMap<String,int> userName2ind = new HashMap<String,int>();
for (int i=0; i<=players.length; i++) {
userName2ind.put(orderedUserNames[i],i+1);
}
它寫出“意外類型”並指向int
。 如果我用String
替換int
而i+1
用i+"1"
替換,則編譯就可以了。 這里有什么問題?
它對Integer
很好,但對int
不行 - Java泛型只能使用引用類型 ,基本上:(
試試這個 - 雖然要知道它會包裝一切:
HashMap<String,Integer> userName2ind = new HashMap<String,Integer>();
for (int i=0; i<=players.length; i++) {
userName2ind.put(orderedUserNames[i],i+1);
}
如果你有小集合,那么使用引用類型可能沒什么問題,但有其他選擇,而且好的是trove4j 。 Trove在使用純原語重新創建集合API方面做得非常好。 收益大大降低了內存使用率,在許多情況下,插入/查找時性能更高。 您的示例如下所示:
TObjectIntHashMap<String> userName2ind = new TObjectIntHashMap<String>();
for (int i=0; i<=players.length; i++) {
userName2ind.put(orderedUserNames[i],i+1);
}
根據我的經驗,唯一的缺點是沒有這些的並發實現,所以你必須找到另一種管理線程安全的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.