我有几个形式的数组:
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?
预先感谢您的任何帮助!
EDIT below
================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()方法