根据 属性 ,我很难 整理我的对象 。
我有这个患者对象列表,我想根据他们的姓氏进行排序,但根本不对它们进行排序。你能告诉我我做错了什么吗?
以下是一些相关的代码。
Patient.java
import java.util.Comparator;
public class Patient implements Comparable<Patient> {
String fname, lname, mname, ID;
public static class OrderByLastName implements Comparator<Patient> {
@Override
public int compare(Patient p1, Patient p2) {
return p1.lname.compareTo(p2.lname);
}
}
public static class OrderByID implements Comparator<Patient> {
@Override
public int compare(Patient p1, Patient p2) {
return p1.ID.compareTo(p2.ID);
}
}
@Override
public int compareTo(Patient another) {
// TODO Auto-generated method stub
return 0;
}
}
MainActivity.java
public class PatientList extends ActionBarActivity {
String[] newFName = {"Mark","Andy","Bryan"};
String[] newLName = {"Uy","Igy","Nator"};
String[] newMName = {"Wi","Menos","Pat"};
String[] newID = {"3","5","1"};
ArrayList<Patient> patientList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createPatientList();
sortPatient(1);
}
private void createPatientList() {
patientList = new ArrayList<Patient>();
for (int i = 0; i < newFName.length; i++) {
Patient patient = new Patient();
patient.lname = newLName[i];
patient.fname = newFName[i];
patient.mname = newMName[i];
patient.ID = newID[i];
patientList.add(patient);
}
}
private void sortPatient(int order){
switch (order) {
case 1:
Collections.sort(patientList, new Patient.OrderByLastName());
break;
case 2:
Collections.sort(patientList, new Patient.OrderByID());
break;
default:
break;
}
}
}
答案 0 :(得分:1)
据我所知,你的代码应该可行,我怀疑单元测试会证明这一点。如果您的问题是您无法看到更新,那么您的视图更新逻辑可能有问题。
答案 1 :(得分:1)
Philip,我刚刚复制了你的代码并将其粘贴到一个java项目中。下面的源代码以及输出的屏幕截图。我没有对Patient课程做任何改动;只是复制并粘贴到我的项目中。
Test.java:
import java.util.ArrayList;
import java.util.Collections;
public class Test {
static String[] newFName = { "Mark", "Andy", "Bryan" };
static String[] newLName = { "Uy", "Igy", "Nator" };
static String[] newMName = { "Wi", "Menos", "Pat" };
static String[] newID = { "3", "5", "1" };
static ArrayList<Patient> patientList;
public static void main(String[] args) {
createPatientList();
System.out.println("Before: ");
for (Patient p : patientList) {
System.out.println(p.lname);
}
sortPatient(1);
System.out.println("\nAfter: ");
for (Patient p : patientList) {
System.out.println(p.lname);
}
}
private static void createPatientList() {
patientList = new ArrayList<Patient>();
for (int i = 0; i < newFName.length; i++) {
Patient patient = new Patient();
patient.lname = newLName[i];
patient.fname = newFName[i];
patient.mname = newMName[i];
patient.ID = newID[i];
patientList.add(patient);
}
}
private static void sortPatient(int order) {
switch (order) {
case 1:
Collections.sort(patientList, new Patient.OrderByLastName());
break;
case 2:
Collections.sort(patientList, new Patient.OrderByID());
break;
default:
break;
}
}
}
屏幕截图: