向TreeSet中添加不同类型的对象进行比较排序,创建TreeSet对象时传入自定义的比较方法

1.首先我们先自定义一个比较器,实现Comparator接口,泛型传入自定义的比较器类对象,重写compare方法进行整体比较排序,在方法中返回比较的结果。

import java.util.Comparator;
//自定义一个比较器,让继承该类的子类整体排序
public class Animal implements Comparator<Animal>{
	private double weight;
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	@Override
	public int compare(Animal dog, Animal cat) {
		return (int) (dog.getWeight() - cat.getWeight());
	}
}

2.然后定义不同类型的子类对象,让它们继承自定义的比较器,并且实现Comparable接口,泛型传入自定义的比较器类对象,并重写compareTo方法,在方法中返回比较的结果,这里也可以返回0。
子类对象1

//让子类继承自定义的比较器Animal类,再实现Comparable接口,让子类排序
public class Cat extends Animal implements Comparable<Animal>{
	private String name;
	private double weight;
	public Cat() {
		super();
	}
	public Cat(String content) {
		String[] data = content.split(",");
		this.name = data[0];
		this.weight = Double.valueOf(data[1]);
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	@Override
	public String toString() {
		return "Cat [name=" + name + ", weight=" + weight + "]";
	}
	public int compareTo(Animal cat) {
		return (int) (this.weight - cat.getWeight());
//		return 0;
	}
}

子类对象2

//让子类继承自定义的比较器Animal类,再实现Comparable接口,让子类排序
public  class Dog extends Animal implements Comparable<Animal>{
	private String type;
	private double weight;
	public Dog() {
		super();
	}
	public Dog(String content) {
		String[] data = content.split(",");
		this.type = data[0];
		this.weight = Double.valueOf(data[1]);
	}

	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	@Override
	public String toString() {
		return "Dog [type=" + type + ", weight=" + weight + "]";
	}
	public int compareTo(Animal dog) {
		return (int) (this.weight - dog.getWeight());
//		return 0;
	}
}

3.写测试类

import java.util.TreeSet;
//测试TreeSet添加两个不同类型的对象 进行比较排序
public class TestTreeSet {
	public static void main(String[] args) {
		TreeSet<Animal> set = new TreeSet<Animal>(new Animal());
		set.add(new Dog("柴犬,3.5"));
		set.add(new Dog("柯基,7.5"));
		set.add(new Dog("藏敖,5.5"));
		set.add(new Cat("橘猫,6.5"));
		set.add(new Cat("花猫,4.5"));
		set.add(new Cat("胖猫,9.5"));
		for (Object object : set) {
			System.out.println(object);
		}
	}
}

4.测试结果:如:按照体重进行排序
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值