[英]How to pass an array of primitive types as object array in java?
I wanted the following function to be generic for all data types. 我希望以下函数对所有数据类型通用。 However, this does not work with the primitive data types.
但是,这不适用于原始数据类型。 Why is that?
这是为什么? Can anyone give a solution to this?
任何人都可以解决这个问题吗? I would greatly appreciate it.
我将不胜感激。
private int getIndexOfElement(Object x, Object[] xArray){
for(int i=0; i<xArray.length;i++){
if(xArray[i]==x){
return i;
}
}
return -1;
}
Your method getIndexOfElement(int,Object[])
accepts any array of type, that extends Object
. 您的方法
getIndexOfElement(int,Object[])
接受任何扩展Object
的类型的数组。 Since int
is primitive type - not a class type, you can not pass int[]
to the method. 由于
int
是原始类型-不是类类型,因此无法将int[]
传递给该方法。 However, you can use Integer
class: 但是,您可以使用
Integer
类:
Integer[] ints = new Integer[]{1,2,3,4,5};
Integer i = 5;
int index = getIndexOfElement(i, ints);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.