0

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;
    }
4
  • 5
    Primitives are not objects. Simple. This cannot be done. Commented Jan 30, 2016 at 1:14
  • Something like this can be done with reflection using java.lang.reflect.Array, but almost certainly not recommended. Reflection is clunky and error-prone so you'd think carefully about whether it's actually a good decision to use it. Useful to know about, though. Commented Jan 30, 2016 at 1:34
  • In Java 8 you can use this: Arrays.stream( data ).boxed().toArray( Integer[]::new ) to convert a primitives array to an objects array. Commented Jan 30, 2016 at 1:52
  • @Titus are you suggesting copying the whole array to a new array just to find the index? That seems somewhat...unwise. Commented Jan 30, 2016 at 11:27

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.