[英]indexOf() using ArrayList in java
I've a class A
which is as follows:我有一个
A
类,如下所示:
A{
String name;
ArrayList<Bike> firstArray;
ArrayList<Cycle> secondArray;
// it's constructors and related methods are down lines.
}
and I have two instances of it named a_Obj
and b_obj
.我有两个名为
a_Obj
和b_obj
实例。 I compare only the variable , name
inside object a_Obj
with b_Obj
using indexOf
.我使用
indexOf
仅比较对象a_Obj
和b_Obj
的变量name
。
My question is how to call indexOf
in this case and in other words how to tell the compiler that I just want to compare name
of two objects regardless of ArrayLists declared inside the class A
.我的问题是在这种情况下如何调用
indexOf
,换句话说,如何告诉编译器我只想比较两个对象的name
,而不管类A
声明的 ArrayLists 是什么。
你可以在你的班级中覆盖 equals()
Given below is how indexOf
has been implemented by default:下面给出了默认情况下
indexOf
实现方式:
public int indexOf(Object o) {
ListIterator<E> it = listIterator();
if (o==null) {
while (it.hasNext())
if (it.next()==null)
return it.previousIndex();
} else {
while (it.hasNext())
if (o.equals(it.next()))
return it.previousIndex();
}
return -1;
}
By overriding the equals
method in A
to consider just the equality of name
, you can make it happen.通过覆盖
A
的equals
方法以仅考虑name
的相等性,您可以实现它。
Given below is the definition generated by Eclipse IDE:下面给出的是 Eclipse IDE 生成的定义:
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
A other = (A) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
A shorter version for the same can be as follows:相同的较短版本如下:
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
A other = (A) obj;
return Objects.equals(name, other.name);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.