TreeSet的两种排序方法

简介:

TreeSet的两种排序方法:自然排序和定义比较器,推荐使用定义比较器方法。

<span style="color:#333333;">import java.util.*;
class treeset 
{
	public static void main(String[] args) 
	{
		TreeSet t = new TreeSet();
//		TreeSet t = new TreeSet(new mycomparator());//第二种方法定义
		t.add(new student("a1",18));
		t.add(new student("a2",18));
		t.add(new student("a1",18));
		t.add(new student("a3",16));
		t.add(new student("a4",25));

		for(Iterator it = t.iterator();it.hasNext();)
		{
			student s = (student)it.next();
			sop(s.getName()+","+s.getAge());
		}
	}
	public static void sop(Object obj)
	{
		System.out.println(obj);
	}
}

/*
自然排序法 定义Comparable接口,覆盖CompareTo方法
*/
class student implements Comparable
{
	private String name;
	private int age;
	student(String name,int age)
	{
		this.name = name;
		this.age = age;
	}
	public int compareTo(Object obj)
	{
		if(!(obj instanceof student))
			throw new RuntimeException("不是学生");
		student s = (student)obj;
		if(this.age>s.age)
			return 1;
		if(this.age==s.age)
			return this.name.compareTo(s.name);
		return -1;

	}
	public String getName()
	{
		return name;
	}
	public int getAge()
	{
		return age;
	}
}

/*
定义比较器   当两种方法都存在时,以比较器为主。
定义一个类,实现Comparator接口,覆盖compare方法
*/
class mycomparator implements Comparator
{
	public int compare(Object o1,Object o2)
	{
		student s1 = (student)o1;
		student s2 = (student)o2;

		int num = s1.getName().compareTo(s2.getName());
		if(num ==0)
		{
			if(s1.getAge()>s2.getAge())
				return 1;
			if(s1.getAge()==s2.getAge())
				return 0;
			return -1;
		}
		return num;
	}
}</span>


目录
相关文章
|
7月前
|
搜索推荐 算法 测试技术
C++桶排序算法的应用:存在重复元素 III
C++桶排序算法的应用:存在重复元素 III
|
8月前
TreeMap的排序
TreeMap的排序
40 0
|
4月前
|
存储 算法 搜索推荐
排序方法8大总结
排序方法8大总结
|
11月前
|
算法 Java
用Java实现冒泡排序和Arrays排序
用Java实现冒泡排序和Arrays排序
46 0
|
11月前
TreeMap实现排序
TreeMap实现排序
|
11月前
|
算法 搜索推荐 Java
数组的四种排序方法介绍
数组的四种排序方法介绍
259 0
|
存储 安全 API
TreeSet详解
TreeSet详解
122 0
TreeSet详解
TreeSet的两种排序方式
示例: 示例公用类: public class MyDate { private int month; private int year; private int day; @Override public String toString() { return "MyDate{" + "month=" + month + ", year=" + year +
79 0
TreeSet的两种排序方式
|
存储
TreeSet相关问题
TreeSet相关问题
|
存储 算法 Java
TreeSet类的排序问题
TreeSet支持两种排序方法:自然排序和定制排序。TreeSet默认采用自然排序。1、自然排序    TreeSet会调用集合元素的compareTo(Object obj)方法来比较元素之间大小关系,然后将集合元素按升序排列,这种方式就是自然排序。
1633 0