Reputation: 11
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;
}
Upvotes: 0
Views: 337
Reputation:
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);
Upvotes: 3