我是Java初學者。我需要按字母順序對一串名稱進行排序。我有一個類從文本文件中讀取并寫入按年齡(小于 18 歲)過濾的排序文件,但我需要它按字母順序過濾,下面是我的實現。它在沒有按名稱過濾的情況下工作正常。 public class PatientFileProcessor { public void process(File source, File target) { System.out.println("source"+source.getAbsolutePath()); System.out.println("target"+target.getAbsolutePath()); try { writefile(target, filterbyAge(readfile(source))); } catch (Exception ex) { Logger.getLogger(PatientFileProcessor.class.getName()).log(Level.SEVERE, null, ex); } } public List<Patient> readfile(File source) throws Exception { List<Patient> patients = new ArrayList(); BufferedReader bf = new BufferedReader(new FileReader(source)); String s = bf.readLine();// ignore first line while ((s = bf.readLine()) != null) { String[] split = s.split("\\|"); System.out.println(Arrays.toString(split)); System.out.println(s+" "+split[0]+" "+split[1]+" "+split[2]); Date d = new SimpleDateFormat("yyyy-dd-MM").parse(split[2]); patients.add(new Patient(split[0], split[1], d)); } return patients; } public void writefile(File target, List<Patient> sorted) throws Exception { BufferedWriter pw = new BufferedWriter(new FileWriter(target)); DateFormat df = new SimpleDateFormat("yyyy/dd/MM"); for (Iterator<Patient> it = sorted.iterator(); it.hasNext();) { Patient p = it.next(); pw.append(p.getName() + "|" + p.getGender() + "|" + df.format(p.getDob())); pw.newLine(); } pw.flush(); }我該怎么做?
3 回答

守著星空守著你
TA貢獻1799條經驗 獲得超8個贊
您可以做的是您可以Comparable
在您的接口中實現接口Patient
并覆蓋該compareTo
方法。這樣,當 Collections 的 sort 方法被調用時,它會使用你的 compareTo 方法進行比較。
添加回答
舉報
0/150
提交
取消