为什么我不能在 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
Why can I not create a HashMap with 'long' types in Java?
提问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 的盒装版本。