Java ArrayList IndexOf-查找对象索引
假设我有一节课Java ArrayList IndexOf-查找对象索引,java,arraylist,Java,Arraylist,假设我有一节课 public class Data{ public int k; public int l; public Data(int k, int l){ this.k = k; this.l = l; } public boolean equals(Date m){ if(this.k == m.k && this.l = m.l) return true;
public class Data{
public int k;
public int l;
public Data(int k, int l){
this.k = k;
this.l = l;
}
public boolean equals(Date m){
if(this.k == m.k && this.l = m.l)
return true;
return false;
}
}
我向ArrayList添加了几个数据对象:
ArrayList<Data> holder = new ArrayList<Data>;
Data one = new Data(0,0);
Data two = new Data(0,4);
Data three = new Data(0,5);
indexOf是否比我自己查看整个数组列表更好?或者我遗漏了什么。方法确实贯穿了整个列表。以下是Java 7源代码的摘录:
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
public int indexOf(对象o){
如果(o==null){
对于(int i=0;i
最好让Java来完成,而不是自己编写。只要确保你的equals
方法足以找到你想要的对象。您还需要覆盖hashCode()
我不会写出你的equals
方法,但我建议你至少:
- 检查空值
- 测试您正在比较的实例是否相同
- 如果(boolean_expr){return true;},则不需要执行
;只需返回布尔表达式
- 确保您实际上正在重写
方法-该方法的签名需要equals
参数,而不是对象
日期
如果您使用eclise编辑代码,eclipse将从“源”菜单为您生成一个好的equals和hashcode方法。您的
equals方法的签名是错误的。您没有覆盖对象
中的equals
,只是重载了它
要覆盖对象
中equals
方法的行为,您的签名必须与对象
中的签名完全匹配。试试这个:
public boolean equals(Object o) {
if(!(o instanceof Data)) return false;
Data other = (Data) o;
return (this.k == other.k && this.l == other.l);
}
此外,正如其他人所建议的,重写hashCode方法也是一个好主意,这样您的对象也可以在基于地图的集合中正常工作。Makoto的答案是正确的。我也会这么说。但是上面的代码中有一些错误
你写了“公共布尔等于(日期m){”。我想,你指的是数据而不是日期
您编写了“if(this.k==m.k&&this.l=m.l)”。if查询中的第二个条件必须是“==”
关于你的问题:
Makoto的答案是一个解决方案。
我的解决方案是在eclipse的帮助下自动生成hashcode和equals方法。如下所示:
public class Data {
// your class code here
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + k;
result = prime * result + l;
return result;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Data)) {
return false;
}
Data other = (Data) obj;
if (k != other.k) {
return false;
}
if (l != other.l) {
return false;
}
return true;
}
}
问题是您没有重写equals
方法,而是重载。Nope-indexOf
使用equals
。
public class Data {
// your class code here
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + k;
result = prime * result + l;
return result;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Data)) {
return false;
}
Data other = (Data) obj;
if (k != other.k) {
return false;
}
if (l != other.l) {
return false;
}
return true;
}
}