Qichao Ying
Qichao Ying

Reputation: 80

Java : To write a method that can be applied on any kind of array

Hi and thanks for noticing my problem. I want to write a method that can be used by different types of arrays. But my code always looks like this:

public int indexOf_1(int[] a,int b){
    //Find the first matched result and return, otherwise report -1
    int index = -1;
    for(int j=0;j<a.length;j++){
        if (a[j]==b) 
        {index=j;}
    }
    return index;
}

public int indexOfChar_1(char[] a,int b){
    //Consider merged to the previous method?
    int index = -1;
    for(int j=0;j<a.length;j++){
        if (a[j]==b) 
        {index=j;}
    }
    return index;
}

That seems to be redundant and I'm completely uncomfortable with such code duplication. Is there any way to write a searching method for all kinds of array to avoid repeating in this case? Thanks!

Upvotes: 3

Views: 108

Answers (3)

Runze Liu
Runze Liu

Reputation: 11

public static <T> int index_Of(Object[] input,T value){
    //Find the first matched result and return, otherwise report -1
    for(int j=0;j<input.length;j++){
        if(input[j].equals(value))
            return j;
    }
    return -1;
}

You can generalize you method to deal with all kind of arrays. However, please pay more attention to the type. If you want to use Object referring to primitive type, when declaring a primitive type array, you need to use reference type. For example,

Character [] a = new Character[]{'a','b','c'};

DO NOT use char, since it will compile error when type checking.

Upvotes: 1

mattmess1221
mattmess1221

Reputation: 4444

Unfortunately because the way arrays and the JVM work, this can't be reduced. Not even generics can help since int[] cannot be safely cast to Object[] without explicit conversion.

This looks like a common util function. If you're not comfortable with the code duplication, you can consider using one of the many libraries which provide this functionality. Guava and Commons-Lang are a few.

Guava puts them in the class relevant to the primitive type. Commons-Lang arranges them in the ArrayUtils class

e.g.

Bytes.indexOf(byteArray, (byte) 2);
Ints.indexOf(intArray, 22);
ArrayUtils.indexOf(intArray, 6);

Upvotes: 3

JBirdVegas
JBirdVegas

Reputation: 11413

Well you could use Object[] but you might not want to use ==, since it will compare identity of objects instead of values, instead you probably want to use .equals(). (Unless you know the value will always be a char or int) Perhaps this:

public int indexOf(Object[] a, int b) {
    int index = -1;
    for (int j = 0; j < a.length; j++) {
        if (a[j].equals(b)) {
            index = j;
        }
    }
    return index;
}

Upvotes: 1

Related Questions