Getting the index of an element in a list of non-primitive type

Here is my Info class

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

      

and

List<Info> Records;

      

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

+3


source to share


3 answers


You can implement 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 this is good practice though, expecting up or down votes;)

+3


source


There is List

no method in the interface to find objects based on an object attribute. Thus, you need to iterate through your list.

Best used Map

to provide matching key value pairs for your needs. Map

definitely a better choice because with Map you should be able to get the object you want with O (1) complexity instead of O (n) versus iterating over a list.



You can use it imei

as a key for your map and the corresponding object Info

as a value.

+5


source


If you need an index, maintain Map

your object Info

with String as the key, which is yours imei

(assuming it's unique.).

Otherwise there is no way to get it directly from the list without going through (looping) the List.

+1


source







All Articles