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
. Since int
is primitive type - not a class type, you can not pass int[]
to the method. However, you can use Integer
class:
Integer[] ints = new Integer[]{1,2,3,4,5};
Integer i = 5;
int index = getIndexOfElement(i, ints);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.