AndreaF
AndreaF

Reputation: 12395

Method that receives different generic lists doesn't work due to incompatible types

I have created a method that returns me the index of the first occurence of an element in list in this way

public int getOccurrenceIndex(ArrayList<Object> list, Object o){
        Object tmp;
        for(int i=0; i<list.size(); i++){
            tmp=list.get(i);
            if(tmp.equals(o)){
                return i;
            }
        }
        return -1;
    }

I want to use this with different arrayList for example with

ArrayList<Car> carList, Car c

or

ArrayList<Person> personList, Person p

etc.

without define a separate method for each type

Any suggestion?

Upvotes: 2

Views: 73

Answers (2)

Kick
Kick

Reputation: 4923

Use java Generics,now you can pass any class as below :

public  <T> int getOccurrenceIndex(ArrayList<T> list, T o){
        T tmp;
        for(int i=0; i<list.size(); i++){
            tmp=list.get(i);
            if(tmp.equals(o)){
                return i;
            }
        }
        return -1;
    }

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213351

Make that method generic. Also, rather than having ArrayList as parameter, use List, so that it can work with any implementation of List:

public <T> int getOccurrenceIndex(List<T> list, T o){
    T tmp;
    for(int i=0; i<list.size(); i++){
        tmp = list.get(i);
        if(tmp.equals(o)){
            return i;
        }
    }
    return -1;
}

BTW, why do you want to write your own method, instead of using ArrayList#indexOf(Object) method?

Upvotes: 1

Related Questions