-
package
v08;
-
-
import
java.util.*;
-
public
class
TestSort {
-
-
public
static
void
main(String[]
args
) {
-
//
TODO
Auto-generated method stub
-
List
l1
=
new
LinkedList
();
-
l1
.add(
new
Name(
"Karl"
,
"M"
))
;
-
l1
.add(
new
Name(
"Steven"
,
"Lee"
))
;
-
l1
.add(
new
Name(
"John"
,
"O"
))
;
-
l1
.add(
new
Name(
"Tom"
,
"M"
))
;
-
System.
out
.println(
l1
);
[
Karl
M,
Steven
Lee, John O, Tom M]
-
Collections.
sort
(
l1
)
;
-
System.
out
.println(
l1
);
//[John O,
Karl
M,
Steven
Lee, Tom M]
-
List
l2
=
new
LinkedList
();
-
l2
.add(
"String"
)
;
-
l2
.add(
new
Integer(100))
;
-
System.
out
.println(
l2
);
//集合的toString方法就是每个元素(对象)的toString方法联合[String, 100]
-
-
-
-
}
-
-
}
-
-
class
Name
implements
Comparable
{
-
-
private
String
firstName
,
lastName
;
-
-
public
int
compareTo(Object
obj
){
-
Name
name
= (Name)
obj
;
-
int
a
=
lastName
.compareTo(
lastName
);
-
return
a
!= 0 ?
a
:
-
firstName
.compareTo(
name
.
firstName
);
-
}
-
-
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();
-
}
-
}
-