为什么我不能在 Java 中创建具有“long”类型的 HashMap?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27211582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:24:04  来源:igfitidea点击:

Why can I not create a HashMap with 'long' types in Java?

javahashmap

提问by Kumar Vaibhav

Any reason that the following is not allowed?

有什么理由不允许以下行为?

HashMap<long, long> x = new HashMap<>();

回答by Master Slave

you're using primitives rewrite to HashMap<Long,Long> x = new HashMap<>()

你正在使用原语重写 HashMap<Long,Long> x = new HashMap<>()

回答by KeyboardDrummer

In Java, types with generic type parameters, such as HashMap, only accept types that inherit from Object. long does not inherit from Object, so you can't use it with HashMap. You can however use Long, which is a boxed version of long.

在 Java 中,具有泛型类型参数的类型,例如 HashMap,只接受从 Object 继承的类型。long 不是从 Object 继承的,因此您不能将它与 HashMap 一起使用。但是,您可以使用 Long,它是 long 的盒装版本。

回答by bedrin

Using standard collections for primitive types like long is not really effective

对像 long 这样的原始类型使用标准集合并不是很有效

If you need to minimize memory footprint and get better performance you should consider 3rd-party collection libraries like Trove

如果你需要最小化内存占用并获得更好的性能,你应该考虑像Trove这样的 3rd-party 集合库