知识点:
1、Collections的使用。
2、自定义类泛型的使用。
3、自定义类,toString();equals();hashCode()方法的重写。
1 import java.util.*;
2
3 public class MyComparableTest{
4 public static void main(String[] args) {
5 List<Name> a=new LinkedList<Name>();
6 a.add(new Name("shang","zeng"));
7 a.add(new Name("qi","li"));
8 a.add(new Name("mei","niang"));
9 a.add(new Name("peingfei","chen"));
10
11 System.out.println(a);
12 Collections.sort(a);
13 System.out.println(a);
14
15
16 System.out.println(a.remove(new Name("peingfei","chen")));
17 System.out.println(a);
18
19 }
20 }
21
22 class Name implements Comparable<Name>{
23 String firstname,lastname;
24
25 public Name(String firstname,String lastname){
26 this.firstname=firstname;
27 this.lastname=lastname;
28 }
29
30 public String toString(){
31 return(firstname+" "+lastname);
32 }
33
34 /* //equals()method one
35 public boolean equals(Object obj){
36 if (obj==null){ return false; }
37 else
38 { if(obj instanceof Name)
39 {
40 Name n = (Name)obj;
41 if (this.firstname.equals(n.firstname) && this.lastname.equals(n.lastname)){return true;}
42 }
43
44 return false;
45 }
46 }
47 */
48 // equals()methoed two
49 public boolean equals(Object obj){
50 if(obj instanceof Name){
51 Name n=(Name)obj;
52 return (this.firstname.equals(n.firstname))
53 && (this.lastname.equals(n.lastname));
54 }
55
56 return super.equals(obj);
57 }
58
59 public int hashCode(){ return firstname.hashCode(); }
60
61 public int compareTo(Name o){
62 int lastnamecompare=lastname.compareTo(o.lastname);
63 return
64 (lastnamecompare!=0?lastnamecompare:firstname.compareTo(o.firstname));
65 }
66 }