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>


目录
相关文章
|
3月前
|
C++ 索引
存在重复元素 II(C++)
存在重复元素 II(C++)
16 0
|
7月前
TreeMap的排序
TreeMap的排序
40 0
|
3月前
|
存储 算法 搜索推荐
排序方法8大总结
排序方法8大总结
|
8月前
TreeSet集合
TreeSet集合
28 0
|
8月前
|
索引 容器
存在重复元素II
存在重复元素II
41 0
|
10月前
TreeMap实现排序
TreeMap实现排序
|
10月前
|
算法
存在重复元素
存在重复元素
30 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 +
78 0
TreeSet的两种排序方式
|
存储
TreeSet相关问题
TreeSet相关问题

热门文章

最新文章