java中TreeSet的两种排序比较的方式

第一种是使得元素具有比较性

第二种是让集合具有比较性

具体代码步骤如下:

import java.util.*;
/*
 * TreeSet:可以自动对对集合中的元素进行排序
 * 第一种比较方式
 * 步骤:
 * 1.让元素对象的类具有比较性,并实现Comparable接口
 * 2.对其中的compareto方法进行复写
 * 3.在方法中定义返回1大于0等于-1小于
 * 4.在主函数中加入元素并用迭代器取出可看到结果
 */
class student implements Comparable<Object>
{
	private String name;
	private int age;
	student(String name,int age)//将变量定为私有,并提供方法,在构造函数中初始化,是对象的一种封装方式
	{
		this.name=name;
		this.age=age;
	}
	public String getname()
	{
		return name;
	}
	public int getage()
	{
		return age;
	}
	public int compareTo(Object obj)//复写方法
	{
		if(!(obj instanceof student))//判断传进来的是否为学生对象
		{
			throw new RuntimeException("不是学生对象");
		}
		student s=(student)obj;//将obj向下转型,才能调用子类特有的方法
		if(this.age>s.age)
		{
			return 1;
		}
		if(this.age==s.age)//如果年龄相同的话,我们就比较名字
		{
			return this.name.compareTo(s.name);
		}
		return -1;
	}
}
public class Treeset1 {

	public static void main(String[] args) 
	{
		TreeSet<student> ts=new TreeSet<student>();
		ts.add(new student("zhangsan",20));
		ts.add(new student("lisi",18));
		ts.add(new student("wangwu",18));
		ts.add(new student("zhaosi",22));
		Iterator<student> it=ts.iterator();
		while(it.hasNext())
		{
			student stu=(student)it.next();
			System.out.println(stu.getname()+"....."+stu.getage());
		}
		
		
	}

}
import java.util.*;
/*
 * TreeSet的第二种比较方式
 * 步骤:
 * 1.定义一个自定义比较器,实现Comparator接口
 * 2.复写compare方法
 * 3.将比较器作为参数传到TreeSet当中
 * 4.加入元素就可比较了
 */
class student1
{
	String name;
	int age;
	student1(String name,int age)
	{
		this.name=name;
		this.age=age;
	}
	public String getname()
	{
		return name;
	}
	public int getage()
	{
		return age;
	}
}
class mycompare implements Comparator<Object>
{
	public int compare(Object o1,Object o2)
	{
		student1 s1=(student1)o1;
		student1 s2=(student1)o2;
		if(s1.age>s2.age)
		{
			return 1;
		}
		if(s1.age==s2.age)//如果年龄相同的话,我们就比较名字
		{
			return s1.name.compareTo(s2.name);
		}
		return -1;
	}
}
public class Treeset2 
{

	public static void main(String[] args) 
	{
		TreeSet<student1> ts=new TreeSet<student1>(new mycompare());
		ts.add(new student1("zhangsan",20));
		ts.add(new student1("lisi",18));
		ts.add(new student1("wangwu",18));
		ts.add(new student1("zhaosi",22));
		Iterator<student1> it=ts.iterator();
		while(it.hasNext())
		{
			student1 stu=(student1)it.next();
			System.out.println(stu.getname()+"....."+stu.getage());
		}
	}

}

当元素具备比较性,而且还有比较器的时候,以比较器为主。

猜你喜欢

转载自blog.csdn.net/qq_41901915/article/details/81280507