Java noob:仅对象上的泛型? [英] Java noob: generics over objects only?

查看:22
本文介绍了Java noob:仅对象上的泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Java 新手.在编写 Map<> 时,我发现声明 Map 是一个语法错误,而 Map 是可以的.是否只能在 Java 中实例化对象类型上的泛型,而不是基元?如果是这样,对原语的装箱/拆箱是否有明显的性能损失?

I'm new to Java. While coding a Map<>, I found out that declaring Map<int, int> is a syntax error while Map<Integer, Integer> is OK. Is it only possible in Java to instantiate generics over object types, as opposed to primitives? If so, is there a noticeable performance penalty for boxing/unboxing of primitives?

推荐答案

是的,你只能对泛型类型参数使用引用类型,并且是的,由于装箱/拆箱(可以自动完成),会有一些性能损失大多数情况下).

Yes, you can only use reference types for generic type parameters, and yes, there will be some performance penalty due to boxing/unboxing (which can be done automatically for the most part).

这里引用了 Java 泛型常见问题解答:

是否允许原始类型作为类型参数?

没有.只有引用类型可以用作类型参数.ListSet 等参数化类型是非法的.只有引用类型可以用于泛型类型和方法的实例化.我们必须声明一个 List 而不是 List,使用相应的包装器类型作为类型参数.

No. Only reference types can be used as type arguments. A parameterized type such as List<int> or Set<short> is illegal. Only reference types can be used for instantiation of generic types and methods. Instead of List<int> we must declare a List<Integer>, using the corresponding wrapper type as the type argument.

[...] 请注意,缺少原始类型实例化会导致性能下降.自动装箱和取消装箱使得在源代码中使用泛型类型的包装类型实例化非常方便和简洁.但是简洁的符号隐藏了这样一个事实,即虚拟机在幕后创建并使用了许多包装对象,每个包装对象都必须被分配并随后被垃圾收集.使用泛型类型无法实现直接使用原始类型值的更高性能.只有常规类型才能提供使用原始类型值的最佳性能.

[...] Note, that the lack of primitive type instantiations incurs a performance penalty. Autoboxing and -unboxing make the use of wrapper type instantiations of generic types very convenient and concise in the source code. But the concise notation hides the fact that behind the curtain the virtual machine creates and uses lots of wrapper objects, each of which must be allocated and later garbage collected. The higher performance of direct use of primitive type values cannot be achieved with generic types. Only a regular type can provide the optimal performance of using primitive type values.

如果您绝对需要性能,Trove 有许多专门用于原始类型的数据结构,但对于大多数实用目的,将装箱基本类型与 Java Collections Framework 类一起使用应该会产生超出可接受的性能.

If you absolutely need the performance, Trove has many data structures specialized for primitive types, but for most practical purposes, using boxed primitive types with Java Collections Framework classes should yield more than acceptable performance.

这篇关于Java noob:仅对象上的泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆