Java程序爲字符排序對象Java程序爲字符排序對象
請讓我知道我怎麼能可以得到預期的結果
預期輸出: B2 D1 D2 D14 E2
實際輸出: B2 D1 D14 D2 E2
====================================
List<Name> lst = new ArrayList<>();
lst.add(new Name("D",1));
lst.add(new Name("D",14));
lst.add(new Name("D",2));
lst.add(new Name("E",2));
lst.add(new Name("B",2));
Collections.sort(lst, new Comparator<Name>() {
@Override
public int compare(Name n1, Name n2) {
// TODO Auto-generated method stub
String o1=n1.getNm()+n1.getSeatnum();
String o2=n2.getNm()+n2.getSeatnum();
return o1.compareTo(o2);
}
});
for (Name name : lst) {
System.out.println(name.getNm()+name.getSeatnum());
}
=== ==============================
public class Name {
private String nm;
private int seatnum;
public int getSeatnum() {
return seatnum;
}
public void setSeatnum(int seatnum) {
this.seatnum = seatnum;
}
public Name(String nm) {
super();
this.nm = nm;
}
public Name(String nm, int seatnum) {
super();
this.nm = nm;
this.seatnum = seatnum;
}
public String getNm() {
return nm;
}
public void setNm(String nm) {
this.nm = nm;
}
}