我的ArrayList
定义如下:
ArrayList<Doctor> arr = new ArrayList<Doctor>();
Doctor
类包含以下内容:
String name;
String gender;
String speciality;
在arr
arraylist中我添加了100个医生对象。
现在我需要搜索arr
ArrayList以查看是否存在特定的医生对象。
我尝试了以下方法;
boolean contains = maarrp.containsKey(doc.name);
但是,我不想使用keys
或element
对象的Doctor
进行比较。相反,我想比较整个doctor
对象。我怎么能这样做?
答案 0 :(得分:1)
覆盖equals()
类中的hashcode()
和Doctor
方法。
你的课应该是这样的:
class Doctor
{
String name;
String gender;
String speciality;
public boolean equals()
{
//some logic on which you want to say
//two doctors are same.
return true;
}
public int hashCode()
{
return 0;
}
}
对于hashCode,您必须遵循以下规则:
每当在执行Java应用程序期间多次在同一对象上调用它时,hashCode方法必须始终返回相同的整数,前提是不修改对象的equals比较中使用的信息。从应用程序的一次执行到同一应用程序的另一次执行,该整数不需要保持一致。 如果两个对象根据equals(Object)方法相等,则对两个对象中的每一个调用hashCode方法必须生成相同的整数结果。 如果两个对象根据equals(java.lang.Object)方法不相等,则不需要在两个对象中的每一个上调用hashCode方法必须生成不同的整数结果。但是,程序员应该知道为不等对象生成不同的整数结果可能会提高哈希表的性能。
注意:hashCode不能总是返回0 :)
答案 1 :(得分:1)
您需要在Doctor对象中实现equals()
和hashcode()
方法,然后在下面搜索ArrayList。
ArrayList<Doctor> arr = new ArrayList<Doctor>();
arr.add(new Doctor());
arr.add(new Doctor());
arr.add(new Doctor());
arr.add(new Doctor());
if(arr.contains(doc){
}
创建您的Doctor类,如下所示
class Doctor{
Long id;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Doctor other = (Doctor) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
答案 2 :(得分:1)
覆盖Doctor Class
中的equals()
和hashcode()
方法
/*add a unique id field in doctor class to make each doctor unique.*/
String docUniqueId;
String name;
String gender;
String speciality;
@Override
public boolean equals(Object ob) {
if (!ob instanceof Doctor ) return false;
Doctor that = (Doctor )ob;
return this.docUniqueId== that.docUniqueId;
}
@Override
public int hashCode() {
return docUniqueId;
}
答案 3 :(得分:0)
您可以实现Doctor类的equals()和hashcode()方法。调用ArrayList对象的contains()方法时会调用这些方法。
为了简化这项工作,您最终可以使用提供以下内容的commons-lang库:
EqualsBuilder(http://commons.apache.org/proper/commons-lang/apidocs/index.html?org/apache/commons/lang3/builder/ToStringBuilder.html)
和HashCodeBuilder(http://commons.apache.org/proper/commons-lang/apidocs/index.html?org/apache/commons/lang3/builder/HashCodeBuilder.html)