用java编写一个小程序

1,选用合适的集合类,2,实现对用户输入的单词做排序和查找
2024-11-08 06:10:51
有1个网友回答
网友(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;
}
}