List和Set排序的实现

List、Set、Map的区别

List和Set继承了Collection接口。

List以特定索引来存取元素,可以有重复元素。Set不能存放重复元素(用对象的equals()方法来区分元素是否重复)。Map保存键值对(key-value pair)映射,映射关系可以是一对一或多对一。Set和Map容器都有基于哈希存储和排序树的两种实现版本,基于哈希存储的版本理论存取时间复杂度为O(1),而基于排序树版本的实现在插入或删除元素时会按照元素或元素的键(key)构成排序树从而达到排序和去重的效果。

TreeSet的排序实现:

 1 public class Student implements Comparable<Student> {
 2 
 3     private String name; // 姓名
 4     private int age; // 年龄
 5 
 6     public Student(String name, int age) {
 7         this.name = name;
 8         this.age = age;
 9     }
10 
11     @Override
12     public int compareTo(Student o) {
13 
14         //升序排序
15           return this.age - o.age;
16         //降序排序
17         //return this.age - o.age;
18     }
19 
20     @Override
21     public String toString() {
22         return "Student [name=" + name + ", age=" + age + "]";
23     }
24 
25 }
//测试类
public
class Test1 { public static void main(String[] args) { Set<Student> set=new TreeSet<>(); set.add(new Student("a", 22)); set.add(new Student("b", 12)); set.add(new Student("c", 32)); set.add(new Student("d", 21)); for (Student s:set) { System.out.println(s); } /** * 输出结果 Student [name=b, age=12] Student [name=d, age=21] Student [name=a, age=22] Student [name=c, age=32] */ } }

ArraList的排序:

 1 public class Student2 {
 2 
 3     private String name; // 姓名
 4     private int age; // 年龄
 5 
 6     public Student2(String name, int age) {
 7         this.name = name;
 8         this.age = age;
 9     }
10 
11     public String getName() {
12         return name;
13     }
14 
15     public void setName(String name) {
16         this.name = name;
17     }
18 
19     public int getAge() {
20         return age;
21     }
22 
23     public void setAge(int age) {
24         this.age = age;
25     }
26 
27     @Override
28     public String toString() {
29         return "Student2 [name=" + name + ", age=" + age + "]";
30     }
31     
32 }
//测试类
public
class Test2 { public static void main(String[] args) { List<Student2> list=new ArrayList<>(); list.add(new Student2("a", 22)); list.add(new Student2("b", 12)); list.add(new Student2("c", 32)); list.add(new Student2("d", 21)); //通过sort方法的第二个参数传入一个Comparator接口对象 相当于是传入一个比较对象大小的算法到sort方法中 Collections.sort(list,new Comparator<Student2>() { @Override public int compare(Student2 arg0, Student2 arg1) { //降序排序 return arg1.getAge()-arg0.getAge(); } }); for(Student2 s:list){ System.out.println(s); } /** * 输出结果 Student2 [name=c, age=32] Student2 [name=a, age=22] Student2 [name=d, age=21] Student2 [name=b, age=12] */ } }

 

posted @ 2017-04-26 16:17  Johnson_wang  阅读(10599)  评论(0编辑  收藏  举报