这里的新手爪哇学生。我有一个ArrayList,它包含包含字符串和int的对象。对象的构造函数的结构类似于这个MyClass(String, String, int, int, String)。我想在构造函数中使用String的第一个实例来查找ArrayList元素的索引,但是我很难理解如何实现它。我尝试过使用indexOf(),但没有成功地找到特定元素的索引。如果有人能给我指明正确的方向,我将不胜感激。干杯
发布于 2013-12-10 12:06:57
在MyClass中,您必须重写等于。根据您想要实现的目标,您的等价物方法看起来类似于:
public boolean equals(Object o) {
if (o== null) return false;
if (!(o instanceof MyClass)) return false;
MyClass other = (MyClass) o;
if (other.firstString != null && this.firstString != null
&& this.firstString.equals(other.firstString) return true;
return false;
}编辑:您也应该覆盖hashCode。在重写hashCode时,应该考虑重写等于时所考虑的对象。因此,如果您基于属性MyClass测试两个firstString对象是否相等,则应该在hashCode中嵌入firstString。
public int hashCode() {
if (firstString == null) return 31;
return firstString.hashCode();
}EDIT2: ArrayList在调用indexOf时所做的基本工作如下:'for (条目e= header.next;e != header;e= e.next) { if (o.equals(e.element))返回索引;index++;}‘
因此,每次调用indexOf()时,ArrayList都会在对象上调用equals方法。因此,假设您有一个如下列表:
MyClass m1 = new MyClass("this is some random string", other params);
MyClass m2 = new MyClass("this is my target string", other params);
MyClass m3 = new MyClass("this is irrelevant", other params);
list.add(m1);
list.add(m2);
list.add(m3);现在,您想知道包含“这是我的目标字符串”的MyClass对象的索引。所以你打电话给indexOf:
list.indexOf(new MyClass("this is my target string"), other params);并且,根据您的相等实现,它将返回1。
发布于 2013-12-10 12:03:43
您必须研究如何覆盖类中的equals和hashcode方法。这就是Collection的api用来执行这种操作的内容。
发布于 2013-12-10 12:40:20
如果你能避免的话,你不应该首先在列表中存储不同的类型吗?您真正拥有的是具有不同类型属性的对象列表吗?
https://stackoverflow.com/questions/20493968
复制相似问题