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.
Implement equals (and hashCode) in Object1 class based on idNum field, then you use
List.indexOf
like thisor make a special class for seaching
You cannot do this with indexOf. Instead all of the objects in the list should inherit from a common interface - for example
Now you list can be
List<HasIdNum>
and you can loop through it to find the object by id using:To get the index rather than the object do:
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.
Write a small helper method.
Do not forget to return -1 if not found.