LinkedHashSet集合特点:哈希表和链表实现的Set接口,具有可预测的迭代次序。由链表保证元素有序,元素的存储和取出是一致的。由哈希表保证元素唯一,也就是说没有重复的元素。
TreeSet集合特点:元素按照一定的规则进行排序,具体排序方式取决于构造方法。TreeSet():根据其元素的自然排序进行排序。TreeSet(Comparator comparator):根据指定的比较器进行排序。其余和``Set集合特点一样. 自然排序实现Comparable接口,重写compareTo`方法.
比较器排序:使用匿名内部类

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
59
60
61
62
63
package 集合;

public class Student implements Comparable<Student>{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public int compareTo(Student o) {
// TODO Auto-generated method stub
//return 1;//认为s1元素与s2元素相等 。return 1则认为s1比s2大 ,return -1则认为s1比s2小
int num=this.age-o.age;
int num2=num==0?this.name.compareTo(o.name):num;
return num2;
}

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package 集合;

import java.util.TreeSet;

public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<Student> st=new TreeSet<Student>();
Student s1=new Student("1",11);
Student s2=new Student("11",11);
Student s3=new Student("2",22);
Student s4=new Student("3",33);


st.add(s1);
st.add(s2);
st.add(s3);
st.add(s4);

for(Student s:st) {
System.out.println("年龄排序:"+s.getAge());
}
}
}
1
2
3
4
5
6

年龄排序:11
年龄排序:11
年龄排序:22
年龄排序:33

1
2
3
4
5
6
7
8
9
10
11
TreeSet<Student> st=new TreeSet<Student>(new Comparator<Student>() {

@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
int num=o1.getAge()-o2.getAge();
int num2=num==0?o1.getName().compareTo(o2.getName()):num;
return num2;
}
});