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;
}
}
最佳答案
只需比较字母,然后比较您的整数:
public int compare(Name n1, Name n2) {
// TODO Auto-generated method stub
int compare = n1.getNm().compareTo(n2.getNm());
if (compare == 0) {
return Integer.compare(n1.getSeatnum(), n2.getSeatnum());
} else {
return compare;
}
}