简体   繁体   English

为什么Java编译器不喜欢原始int作为HashMap中值的类型?

[英]Why does the Java compiler not like primitive int as type for values in HashMap?

The compiler complains about this code: 编译器抱怨这段代码:

    HashMap<String,int> userName2ind = new HashMap<String,int>();
    for (int i=0; i<=players.length; i++) {
        userName2ind.put(orderedUserNames[i],i+1);
    }

It writes "unexpected type" and point on int . 它写出“意外类型”并指向int If I replace int by String and i+1 by i+"1" , the compilation goes OK. 如果我用String替换inti+1i+"1"替换,则编译就可以了。 What is wrong with in here? 这里有什么问题?

It's fine with Integer , but not okay with int - Java generics only work with reference types , basically :( 它对Integer很好,但对int不行 - Java泛型只能使用引用类型 ,基本上:(

Try this - although be aware it will box everything: 试试这个 - 虽然要知道它会包装一切:

HashMap<String,Integer> userName2ind = new HashMap<String,Integer>();
for (int i=0; i<=players.length; i++) {
    userName2ind.put(orderedUserNames[i],i+1);
}

If you have small collections, then using reference types is probably fine, but there are alternatives and good one is trove4j . 如果你有小集合,那么使用引用类型可能没什么问题,但有其他选择,而且好的是trove4j Trove does a pretty good job of recreating the collections API using pure primitives. Trove在使用纯原语重新创建集合API方面做得非常好。 The payoff is much lower memory usage and in many cases, better performance when inserting/looking up. 收益大大降低了内存使用率,在许多情况下,插入/查找时性能更高。 Your example would look like this: 您的示例如下所示:

TObjectIntHashMap<String> userName2ind = new TObjectIntHashMap<String>();
for (int i=0; i<=players.length; i++) {
    userName2ind.put(orderedUserNames[i],i+1);
}

The only downside, in my experience, is the absence of concurrent implementations of these, so you have to figure out another way to manage thread safety. 根据我的经验,唯一的缺点是没有这些的并发实现,所以你必须找到另一种管理线程安全的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么int原始类型没有在Java中删除 - Why int primitive type not deprectaed in Java 为什么Java编译器允许在三元运算符中将null转换为基本类型 - Why does Java compiler allow casting null to primitive type in ternary operator 在JAVA中,原始数据类型如“ int”是CLASS还是OBJECT? - In JAVA, a primitive data type like “int” a CLASS or an OBJECT? Java:int [] []是原始类型吗? 或者它是否使用clone()方法生成不同的实例? - Java: Is int[][] a primitive type? Or does it generate a different instance with clone() method? 为什么 int 数据类型在 JAVA 中表现得像这样? - Why int data type is behaving like this in JAVA? Java:为什么“long”原始类型不接受简单数字? - Java: why the “long” primitive type does not accept a simple number? 如何在Java中呈现可空的原始类型int? - How to present the nullable primitive type int in Java? 类似于 Java 中的盒装原语的自定义类型 - Custom type that acts like boxed primitive in Java Java - 多 arrays - 行的原始类型 int 没有字段 col - Java - multi arrays - The primitive type int of row does not have a field col 如果结果必须是 int,为什么 Java 编译器允许 int/int 除法? - Why does the Java compiler allow int/int division if the result must be an int?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM