代码:import java.util.*;public class Test {
public static void main(String[] args) {
List c = new LinkedList();
c.add(new Name("f1","l4"));
c.add(new Name("f2","l5"));
c.add(new Name("f2","l7"));
c.add(new Name("f3","19"));
c.add(new Name("f5","l6"));
System.out.println(c);
Collections.sort(c);
System.out.println(c);
}
}class Name implements Comparable {
private String firstName,lastName;
public Name(String firstName, String lastName) {
this.firstName = firstName; this.lastName = lastName;
}
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public String toString() { return firstName + " " + lastName; }
public boolean equals(Object obj) {
if (obj instanceof Name) {
Name name = (Name) obj;
return (firstName.equals(name.firstName))
&& (lastName.equals(name.lastName));
}
return super.equals(obj);
}
public int hashCode() {
return firstName.hashCode();
}
public int compareTo(Object o) {
Name n = (Name)o;
int lastCmp =
lastName.compareTo(n.lastName);
return
(lastCmp!=0 ? lastCmp :
firstName.compareTo(n.firstName));
}
}问题:为什么排序结果是:[f3 19, f1 l4, f2 l5, f5 l6, f2 l7]呢?按理讲,19比17大,应该排在最后啊,怎么回事? 请教~
public static void main(String[] args) {
List c = new LinkedList();
c.add(new Name("f1","l4"));
c.add(new Name("f2","l5"));
c.add(new Name("f2","l7"));
c.add(new Name("f3","19"));
c.add(new Name("f5","l6"));
System.out.println(c);
Collections.sort(c);
System.out.println(c);
}
}class Name implements Comparable {
private String firstName,lastName;
public Name(String firstName, String lastName) {
this.firstName = firstName; this.lastName = lastName;
}
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public String toString() { return firstName + " " + lastName; }
public boolean equals(Object obj) {
if (obj instanceof Name) {
Name name = (Name) obj;
return (firstName.equals(name.firstName))
&& (lastName.equals(name.lastName));
}
return super.equals(obj);
}
public int hashCode() {
return firstName.hashCode();
}
public int compareTo(Object o) {
Name n = (Name)o;
int lastCmp =
lastName.compareTo(n.lastName);
return
(lastCmp!=0 ? lastCmp :
firstName.compareTo(n.firstName));
}
}问题:为什么排序结果是:[f3 19, f1 l4, f2 l5, f5 l6, f2 l7]呢?按理讲,19比17大,应该排在最后啊,怎么回事? 请教~
c.add(new Name("f2","l7"));
c.add(new Name("f3","19"));
c.add(new Name("f5","l6"));因为除了 19 之个,其他数字的第一个字符都是小写字母 l,你把 19 改为 l9 就可以了。