Get index of an arraylist using property of an contained object in java [duplicate]

若如初见. 提交于 2019-12-18 16:34:32

问题


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.


回答1:


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.




回答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.




回答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);
        }
    });


来源:https://stackoverflow.com/questions/20836369/get-index-of-an-arraylist-using-property-of-an-contained-object-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!