Sap*_*sic 7 java android arraylist custom-lists
所以,我有一个自定义类和该类类型的数组列表。现在,我想仅使用构成该类对象的其他属性中可用的 ID 来检索此数组列表中的对象的索引。
在网上看到了一些例子,但我有点困惑,他们重写了 hashCode() 和 equals(),并且在 equals() 中他们检查所有属性,我只想检查 ID 值,因为对于每个对象 ID 都是唯一的。
public class MyClass {
private String ID;
private String name;
private String userName;
private String position;
// Constructors and getters and setters
}
Run Code Online (Sandbox Code Playgroud)
所以,我想要的是,比如说这段代码:
List<MyClass> list=new ArrayList<>();
//Values are populated into list
int i=list.indexOf(someObjectsID); //Where someObjectsID is a String and not a MyClass object
Run Code Online (Sandbox Code Playgroud)
int i 将在列表中拥有 ID 等于 someObjectsID 的 MyClass 对象的 indexOf
对于这个问题,有一个绝对有保证、有效的解决方案。没有什么比这更简单、更高效了。
该解决方案是只编写循环而不是试图变得花哨。
for(int i = 0; i < list.size(); i++){
if (list.get(i).getId().equals(id)) {
return i;
}
}
return -1;
Run Code Online (Sandbox Code Playgroud)
无需搞乱 hashCode 或 equals。无需将索引强制放入并非为其设计的流中。
| 归档时间: |
|
| 查看次数: |
2073 次 |
| 最近记录: |