【发布时间】:2014-04-03 02:50:21
【问题描述】:
我有几个数组的形式:
private static String[] patientNames = { "John Lennon", "Paul McCartney", "George Harrison", "Ringo Starr" };
然后我制作一个这样的 TreeSet:
TreeSet<Patient> patTreeSet = new TreeSet<Patient>();
其中 Patient 是制作“Patient”对象的不同类。
然后我循环遍历数组中的每个元素以创建多个患者并将它们添加到我的patTreeSet,如下所示:
for(int i = 0; i< patientNames.length; i++){
Date dob = date.getDate("MM/dd/yyyy", patientBirthDates[i]);
Patient p = new PatientImpl(patientNames[i], patientSSN[i], dob);
patTreeSet.add(p);
}
但是当我去查看我的patTreeSet.size() 时,它只返回“1”——这是为什么呢?
我知道我的对象运行良好,因为当我尝试做同样的事情但使用ArrayList 时,一切正常。所以我猜我用错了 TreeSet。
如果有帮助,Patient 有一个名为 getFirstName() 的方法,当我尝试执行以下操作时:
Iterator<Patient> patItr = patTreeSet.iterator();
while(patItr.hasNext()){
System.out.println(patItr.next().getFirstName());
}
然后只有“John”打印,显然不应该是这种情况......那么,我完全误用了 TreeSet 吗?
提前感谢您的帮助!
编辑下面
================PatientImpl 类====================
public class PatientImpl implements Patient, Comparable{
Calendar cal = new GregorianCalendar();
private String firstName;
private String lastName;
private String SSN;
private Date dob;
private int age;
private int thisID;
public static int ID = 0;
public PatientImpl(String fullName, String SSN, Date dob){
String[] name = fullName.split(" ");
firstName = name[0];
lastName = name[1];
this.SSN = SSN;
this.dob = dob;
thisID = ID += 1;
}
@Override
public boolean equals(Object p) {
//for some reason casting here and reassigning the value of p doesn't take care of the need to cast in the if statement...
p = (PatientImpl) p;
Boolean equal = false;
//make sure p is a patient before we even compare anything
if (p instanceof Patient) {
Patient temp = (Patient) p;
if (this.firstName.equalsIgnoreCase(temp.getFirstName())) {
if (this.lastName.equalsIgnoreCase(temp.getLastName())) {
if (this.SSN.equalsIgnoreCase(temp.getSSN())) {
if(this.dob.toString().equalsIgnoreCase(((PatientImpl) p).getDOB().toString())){
if(this.getID() == temp.getID()){
equal = true;
}
}
}
}
}
}
return equal;
}
然后所有的getter都在下面,还有Comparable接口的compareTo()方法
【问题讨论】:
-
向我们展示您的
PatientImpl课程。 -
粘贴
Patient的代码 -
TreeSet 依赖于您的 Patient/PatientImpl equals/hashCode/compareTo 方法。它们应该根据 Object/Comparable 契约正确实现。
-
您省略了最重要的部分,即
Patient类的代码。如果Patient不包含equals()和hashCode()的正确实现,它将不起作用。