10

I'm having an list of Object type. In that I have one String property idNum. Now I want to get the index of the object in the list by passing the idNum.

List<Object1> objList=new ArrayList<Object1>();

I don't know how to give objList.indexOf(// Don't know how to give here);

Is it possible to do this without iterating the list. I want to use indexOf() method only.

Aditya
  • 2,876
  • 4
  • 34
  • 30
Monicka Akilan
  • 1,501
  • 5
  • 19
  • 42

3 Answers3

10

Write a small helper method.

 private int getIndexByProperty(String yourString) {
        for (int i = 0; i < objList.size(); i++) {
            if (object1 !=null && object1.getIdNum().equals(yourString)) {
                return i;
            }
        }
        return -1;// not there is list
    }

Do not forget to return -1 if not found.

tkruse
  • 10,222
  • 7
  • 53
  • 80
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • Don't forget to check for `null`s in the list, this piece of code can produce NPE if there is any. – Danstahr Dec 30 '13 at 09:14
  • @Danstahr Of course, Guard checking is very basic. Though edited :) – Suresh Atta Dec 30 '13 at 09:16
  • 1
    Depending on how it is used it may be a fair assumption that the list doesn't contain nulls, so the guard check isn't absolutely required. – Tim B Dec 30 '13 at 09:20
3

Implement equals (and hashCode) in Object1 class based on idNum field, then you use List.indexOf like this

int i = objList.indexOf(new Object(idNum));

or make a special class for seaching

    final String idNum = "1";
    int i = list.indexOf(new Object() {
        public boolean equals(Object obj) {
            return ((X)obj).idNum.equals(idNum);
        }
    });
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • 2
    for this requirement we shouldn't compromise equals and hashcode just to consider this need – jmj Dec 30 '13 at 09:08
2

You cannot do this with indexOf. Instead all of the objects in the list should inherit from a common interface - for example

interface HasIdNum {
    String getIdNum();
}

Now you list can be List<HasIdNum> and you can loop through it to find the object by id using:

for (HasIdNum hid: objList) {
   if (hid.getIdNum().equals(idNumToFind) {
       return hid;
   }
}
return null;

To get the index rather than the object do:

for (int i=0;i<objList.size();i++) {
   HasIdNum hid = objList.get(i);
   if (hid.getIdNum().equals(idNumToFind) {
       return i;
   }
}
return -1;

Alternatively you can use reflection to query the methods of the object, but that will be much slower and much less safe as you lose all the compile time type checking.

Tim B
  • 40,716
  • 16
  • 83
  • 128
  • 1
    `if (hid.getIdNum().equals(idNumToFind)` , `int` doesn't have `equals()` – jmj Dec 30 '13 at 09:12
  • Yes, initially I had it as int then spotted that the question said String, I missed changing that in the interface though. Fixed it now. – Tim B Dec 30 '13 at 09:19