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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With