简体   繁体   中英

Getting index of an item in List of non primitive type

Here is my class Info

public class Info {
    public String imei;
    public Integer delta;
}

and my

List<Info> Records;

Is there a simple way to get the index of an Info, where for example imei is 356307044597945, or I must go through the list, comparing all the elements?

There is no method in List interface to find the objects on the basis of an object attribute. So you need to iterate through your List.

Better use Map to provide a key value pair mappings for your need. Map is definitely a better choice because using Map you will be able to get the desired object with O(1) complexity instead of O(n) when compared to iteration over List.

You may use imei as the key for your map and corresponding Info object as the value.

You could implement the equals/hashCode methods:

public class Info {

    public String imei;
    public Integer delta;

    public Info(String imei) {
        this.imei = imei;
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof Info && obj.imei.equals(imei);
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(new Object[] { imei });
    }

}

Then:

int index = records.indexOf(new Info("356307044597945"));

Not sure if it's a good practice though, waiting for up or down votes ;)

If you want an index,maintain a Map of your Info Object and with String as a Key, which is your imei (assuming that is Unique.).

Otherwise there is no way to directly get it from list without looking (looping) into List.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM