使用java中包含对象的属性获取数组列表的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20836369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:41:41  来源:igfitidea点击:

Get index of an arraylist using property of an contained object in java

javagenericscollectionsarraylist

提问by Monicka Akilan

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.

我有一个对象类型列表。因为我有一个字符串属性 idNum。现在我想通过传递 idNum 来获取列表中对象的索引。

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

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

我不知道怎么给 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.

是否可以在不迭代列表的情况下执行此操作。我只想使用indexOf()方法。

采纳答案by Suresh Atta

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.

如果未找到,请不要忘记返回 -1。

回答by Tim B

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

你不能用 indexOf 做到这一点。相反,列表中的所有对象都应该从一个通用接口继承——例如

interface HasIdNum {
    String getIdNum();
}

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

现在您可以列出 canList<HasIdNum>并且您可以循环遍历它以使用以下 id 查找对象:

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.

或者,您可以使用反射来查询对象的方法,但由于您丢失了所有编译时类型检查,因此速度会慢得多且安全性也会降低。

回答by Evgeniy Dorofeev

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

根据 idNum 字段在 Object1 类中实现 equals(和 hashCode),然后你List.indexOf像这样使用

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