2

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?

AndreaF
  • 11,975
  • 27
  • 102
  • 168

2 Answers2

1

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?

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • thanks, Yes i can use indexOf but since I have to do some other stuff in the same way, I use this as sample to fix the issue. – AndreaF Mar 01 '14 at 17:28
0

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;
    }
Kick
  • 4,823
  • 3
  • 22
  • 29