需要将大量'int'类型传递给泛型数组&集合 [英] Large array of 'int' type needs to be passed to a generic array & collections
问题描述
我从一个函数生成一个大数组(大小> 1000),其元素为 int
类型。我需要将此数组传递给泛型类型数组,但由于泛型类型数组不接受基本类型的数组,我无法这样做。
I am generating a large arrays(size>1000) with elements of int
type, from a function. I need to pass this array to a generic type array but since the generic type array doesnt accept arrays of primitive type, I am unable to do so.
我担心使用 Integer
类型数组因为在创建,性能,使用空间(12字节对象的数组)方面成本很高对于大尺寸阵列。当我需要对数组元素执行一些加法运算时,它会创建不可变的 Integer
。
I fear to use the Integer
type array since it will be costly, in terms of creation, performance, space used(an array of 12 byte objects) when doing so for a large size arrays. More it will create immutable Integer
s when I need to perform some addition operations on the array elements.
最好的方式是什么?
编辑为了消除一些混乱,我需要传递int []签名类型的方法: void setKeys(K ... keys)
。
EDIT Just to remove some confusions around, I need to pass int[] to a method of signature type: void setKeys(K... keys)
.
推荐答案
我想将
int []
传递给此函数:public Query< K> setKeys(K ... keys);
我认为你的意思是 int []
应该是一组键...而不仅仅是一个键。
I assume that you mean that int[]
should be the set of keys ... not just one key.
这是不可能的。泛型类型的类型参数必须是引用类型。您的用例需要 K
为 int
。
That is impossible. The type parameters of a generic type have to be reference types. Your use-case requires K
to be a int
.
您有两种选择:
- 使用
整数
(或可变的int
holder class)并支付性能损失,或 - 放弃使用泛型并更改该方法的签名。
- use
Integer
(or a mutableint
holder class) and pay the performance penalty, or - forgo the use of generics and change the signature of that method.
顺便提一句,整数
类保留了缓存 Integer
小 int
值的对象。如果使用 Integer.valueOf(int)
创建对象,则很有可能获得对预先存在的对象的引用。 (当然,这只能起作用,因为 Integer
对象是不可变的。)
Incidentally, the Integer
class keeps a cache of Integer
objects for small int
values. If you create your objects using Integer.valueOf(int)
there's a good chance that you will get a reference to an pre-existing object. (Of course, this only works because Integer
objects are immutable.)
这篇关于需要将大量'int'类型传递给泛型数组&集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!