直接上代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
package exercise1;
public class Person implements Comparable{
private int id;
private String name;
public Person( int id, String name) {
super ();
this .id = id;
this .name = name;
}
public int getId() {
return id;
}
public void setId( int id) {
this .id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this .name = name;
}
public String toString() {
return "Person [id=" + id + ", name=" + name + "]" ;
}
public int hashCode() {
final int prime = 31 ;
int result = 1 ;
result = prime * result + id;
result = prime * result + ((name == null ) ? 0 : name.hashCode());
return result;
}
public boolean equals(Object obj) {
if ( this == obj)
return true ;
if (obj == null )
return false ;
if (getClass() != obj.getClass())
return false ;
Person other = (Person) obj;
if (id != other.id)
return false ;
if (name == null ) {
if (other.name != null )
return false ;
} else if (!name.equals(other.name))
return false ;
return true ;
}
public int compareTo(Object o) {
if (o instanceof Person){
Person p=(Person)o;
return this .name.compareTo(p.name);
}
return 0 ;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
package exercise1;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;
import org.junit.Test;
//定制排序
public class DisOrder {
@Test
public void unNature(){
Comparator com= new Comparator() {
public int compare(Object o1, Object o2) {
if (o1 instanceof Person && o2 instanceof Person){
Person p1=(Person)o1;
Person p2=(Person)o2;
return p1.getName().compareTo(p2.getName());
}
return 0 ;
}
};
Set set= new TreeSet(com);
set.add( new Person( 111 , "MM" ));
set.add( new Person( 222 , "DD" ));
set.add( new Person( 333 , "GG" ));
for (Object obj:set){
System.out.println(obj);
}
}
//自然排序
@Test
public void nature() {
Set set= new TreeSet();
set.add( "aa" );
set.add( "bb" );
set.add( "ff" );
set.add( "zz" );
for (Object obj:set){
System.out.println(obj);
}
}
}
|
以上这篇浅谈TreeSet中的两种排序方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。