java 姓名排序问题
发布网友
发布时间:2023-10-17 15:58
我来回答
共1个回答
热心网友
时间:2024-04-07 10:06
//现在大概好了!
import java.util.*;
public class Comparable {
public static void main(String[] args) {
List<Name> r2 = new LinkedList<Name>();
r2.add(new Name("yan", "enbo"));
r2.add(new Name("miao", "zhenwei"));
r2.add(new Name("li", "zesong"));
r2.add(new Name("kong", "lingming"));
r2.add(new Name("yan", "wenli"));
System.out.println(r2);
Collections.sort(r2);
System.out.println(r2);
}
}
//要排序的类需要实现Comparable接口
class Name implements java.lang.Comparable<Object>{
String firstname, lastname;
public Name(String q, String p) {
firstname = q;
lastname = p;
}
public String toString() {
return firstname + lastname;
}
//实现Comparable接口的类要写compareTo方法
public int compareTo(Object o) {
Name r = (Name) o;
int t = firstname.compareTo(r.firstname);
return (t != 0 ? t : lastname.compareTo(r.lastname));
}
}