1个回答
展开全部
import java.util.*;
public class TestComparable {
public static void main(String[] args) {
List s = new ArrayList();
s.add(new Name("wang","fei"));
s.add(new Name("wang","hong"));
s.add(new Name("yang","lin"));
s.add(new Name("li","ju"));
s.add(new Name("liu","feng"));
Collections.sort(s);
System.out.println(s);
}
}
class Name implements Comparable {
String firstName;
String lastName;
Name(String firstName,String lastName) {
this.firstName=firstName;
this.lastName=lastName;
}
public boolean equals(Object obj) {
if(obj instanceof Name) {
Name n = (Name)obj;
return (firstName.equals(n.firstName))&& (lastName.equals(n.lastName)) ;
}
return super.equals(obj);
}
public int compareTo(Object obj) {
Name nn = (Name)obj;
int last=lastName.compareTo(nn.lastName);
int first=firstName.compareTo(nn.firstName);
return (first!=0 ? first : last) ;
}
public String toString() {
return firstName+" "+lastName;
}
}
public class TestComparable {
public static void main(String[] args) {
List s = new ArrayList();
s.add(new Name("wang","fei"));
s.add(new Name("wang","hong"));
s.add(new Name("yang","lin"));
s.add(new Name("li","ju"));
s.add(new Name("liu","feng"));
Collections.sort(s);
System.out.println(s);
}
}
class Name implements Comparable {
String firstName;
String lastName;
Name(String firstName,String lastName) {
this.firstName=firstName;
this.lastName=lastName;
}
public boolean equals(Object obj) {
if(obj instanceof Name) {
Name n = (Name)obj;
return (firstName.equals(n.firstName))&& (lastName.equals(n.lastName)) ;
}
return super.equals(obj);
}
public int compareTo(Object obj) {
Name nn = (Name)obj;
int last=lastName.compareTo(nn.lastName);
int first=firstName.compareTo(nn.firstName);
return (first!=0 ? first : last) ;
}
public String toString() {
return firstName+" "+lastName;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询