小言_互联网的博客

java-TreeSet

367人阅读  评论(0)

TreeSet是一个包含有序的且没有重复元素的集合,通过TreeMap实现。

对于自定义数据类型
要么(自然排序)现Comparable接口,重写compareTo方法;
要么(比较器排序)定义Comparator做为参数,传给有参构造器,在匿名内部类中重写compare方法;

否则报 "TreeSetTest.自定义数据类型的类 cannot be cast to java.lang.Comparable" 错误


int compareTo(T o)

比较此对象与指定对象的顺序。如果该对象小于、等于或大于指定对象,则分别返回负整数、零或正整数。

返回负数,按升序排序;返回正数,按降序排序。

import java.util.*;
class Student implements Comparable{
	private String name;
	private int age;
	public Student(){}
	public 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 o) {
		Student s = (Student)o;
		return this.age - s.age;//升序
		//return -(this.age - s.age);//降序
	}
	public String toString(){
		StringBuilder sb = new StringBuilder();
		sb.append("name:");
		sb.append(name);
		sb.append(",age:");
		sb.append(age);
		return sb.toString();
	}	
}
public class TreeSetTest2 {
	public static void main(String[] args) {
		TreeSet ts = new TreeSet();
		ts.add(new Student("Jack",20));
		ts.add(new Student("Jack",20));
		ts.add(new Student("Tom",19));
		ts.add(new Student("Kate",22));
		ts.add(new Student("Jerry",24));
		
		Iterator iter = ts.iterator();
		Student s;
		while(iter.hasNext()) {
			s = (Student)iter.next();
			System.out.println(s);
		}
	}
}

 

public int compare(String o1, String o2) :比较其两个参数的顺序。

两个对象比较的结果有三种:大于,等于,小于。

如果要按照升序排序, 则o1 小于o2,返回(负数),相等返回0,o1大于o2返回(正数);

如果要按照降序排序, 则o1 小于o2,返回(正数),相等返回0,o1大于o2返回(负数)


转载:https://blog.csdn.net/fzq13994952987/article/details/102468642
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场