List,TreeSet,TreeMap实现排序的几种方法

List,TreeSet,TreeMap实现排序的几种方法_第1张图片

集合主要有以上几种,

1、其中HashSet,TreeSet,HashMap,TreeMap是不可重复的,HashSet和HashMap需要通过重写hashCode()和equals来实现去重,而TreeSet和TreeMap需要通过实现Comparable或者Comparator接口来实现去重。

2、HashSet和HashMap不能实现排序,而List,TreeSet,TreeMap可以实现排序,它们需要实现Comparable或者Comparator接口来实现排序,其中List需要调用Collections.sort方法。

3、虽然TreeSet和TreeMap既可以去重也可以排序,但是我们一般用HashSet和HashMap去重,用TreeSet、List和TreeMap排序。

下面是排序举例:

注:Student实现了Comparable接口

package cn.tianliangedu.jihe2;

public class Student implements Comparable{
	private String name;
	private int age;
	private int ID;
	
	public Student() {}
	public Student(String name,int age,int ID)
	{
		this.name = name;
		this.age = age;
		this.ID = ID;
	}
	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;
	}
	public int getID() {
		return ID;
	}
	public void setID(int iD) {
		ID = iD;
	}
	
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + ", ID=" + ID + "]";
	}
	@Override
	public int compareTo(Student o) {
		// TODO Auto-generated method stub
		return -(this.age - o.age);
	}

}
package cn.tianliangedu.jihe2;
import java.util.*;

public class TestSort {

	public static void main(String[] args) {
		testSort2();

	}
	//TreeSet实现排序,需实现Comparator或者Comparable中的一个接口
	//两个接口都实现时,优先使用了Comparator接口
	//Comparable逆序,Comparator正序
	public static void testSort()
	{
                //TreeSet通过实现Comparator()接口进行排序              
                Set set = new TreeSet(new MyComparator());
             //TreeSet通过实现Comparable()接口进行排序,此时Student需实现Comparable()接口
             //Set set = new TreeSet(); 
             set.add(new Student("小明",18,111122321));
             set.add(new Student("小红",15,111122321));
             set.add(new Student("小张",21,111122321));
             System.out.println(set);
       }
       public static void testSort2(){
             List list = new ArrayList();
             list.add(new Student("小明",18,111122321));
             list.add(new Student("小红",15,111122321));
             list.add(new Student("小张",21,111122321));
           //List通过实现Comparator()接口进行排序
           Collections.sort(list,new MyComparator());             
           //List通过实现Comparable()接口进行排序            
           //Collections.sort(list);  //Student需实现Comparable接口
           System.out.println(list);
      }
}

class MyComparator implements Comparator{
@Override
    public int compare(Student o1, Student o2) {
        // TODO Auto-generated method stub        
        return o1.getAge() - o2.getAge();   //升序
    }
}        

你可能感兴趣的:(java)