我有一个List(实际上是a LinkedList),我向它添加了实现equals-method的项目.
问题是我添加了相同但不相同的项(如两个初始化对象).现在,当我想获得第二个项目的索引时,我当然得到第一个项目的元素,因为indexOf搜索相等而不是标识.
我试图创建自己的子类LinkedList并覆盖indexOf-method,但这是不可能的,因为我既无法访问子类Node也无法访问Node-Element first.
这是一个例子:
public class ExampleObject {
int number;
public ExampleObject(){
number = 0;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
ExampleObject other = (ExampleObject) obj;
if (number != other.number) return false;
return true;
}
public static void main(String[] args) {
LinkedList<ExampleObject> list = new LinkedList<ExampleObject>();
ExampleObject one = new ExampleObject();
ExampleObject two = new ExampleObject();
list.add(one);
list.add(two);
System.out.println(list.indexOf(one)); // '0' as expected
System.out.println(list.indexOf(two)); // '0', but I want to get '1'
}
}
Run Code Online (Sandbox Code Playgroud)
我的意图:我需要一个对象列表,我想在那里存储已初始化的对象并在以后编辑它们.
自己做迭代,indexOf只是一个辅助方法:
static int indexOfById(List<?> list, Object searchedObject) {
int i = 0;
for (Object o : list) {
if (o == searchedObject) return i;
i++;
}
return -1;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3604 次 |
| 最近记录: |