Java noob:泛型只能用于对象? [英] Java noob: generics over objects only?

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

问题描述

我是Java新手。在对Map<>进行编码时,我发现在 Map< Integer,Integer> 中声明 Map< int,int> code>确定。在Java中只能实例化对象类型的泛型,而不是基元?如果是这样,那么对于基元的装箱/取消装箱是否会有明显的性能损失?

解决方案

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



Java泛型常见问题解答


允许使用原始类型作为类型参数吗?

只有引用类型可以用作类型参数。
List< int> Set< short> 等参数化类型是非法的。只有引用类型可用于实例化泛型类型和方法。我们必须声明一个 List< Integer> ,而不是使用 List

[...]请注意,缺少原始类型实例会导致性能损失。 Autoboxing和-unboxing在源代码中使用非常方便和简洁的泛型类型的包装类型实例。但简洁的表示隐藏了虚拟机创建并使用大量包装对象的幕后事实,每个包装对象都必须分配并随后进行垃圾收集。泛型类型无法实现直接使用原始类型值的更高性能。


如果您确实需要这些性能, Trove 有许多专门用于原始类型的数据结构,但对于大多数实际用途,在Java Collections Framework类中使用盒装原始类型应该会产生超过可接受的性能。

另见




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).

Here's a quote from the Java Generics FAQs:

Are primitive types permitted as type arguments?

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.

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.

See also

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

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