TreeSet里面放对象,如果同时放入了父类和子类的实例对象,那比较时使用的是父类的compareTo方法,还是使用的子类的compareTo方法,还是抛异常!

package com.echo1;

import java.util.Iterator;
import java.util.TreeSet;


public class CompareTest {
	public static void main(String[] args) {
		TreeSet<Parent> t=new TreeSet<>();
		Parent p=new Parent("P_lzz", 45);
		Parent p1=new Parent("P_lzh", 47);
		Parent p2=new Parent("P_bruce", 24);
		Parent p4=new Parent("P_Luce", 22);
		Children c1=new Children("Jame1",12);
		Children c2=new Children("Jame2",23);
		Children c3=new Children("Jame3",46);
		System.out.println("TreeSet遍历-------");
		t.add(c2);
		t.add(c1);
		t.add(p1);
		t.add(p4);
		t.add(c3);
		t.add(p);
		t.add(p2);
		Iterator<Parent> iterator=t.iterator();
		while(iterator.hasNext()){
			System.err.println(iterator.next());
		}
	}
}

class Parent implements Comparable<Parent>{
	private String name;
	private int age;
	public Parent(){
		System.err.println("Parent无参构造器"+name+":"+age);
	};
	public Parent(String name,int age){
		this.name=name;
		this.age=age;
		System.err.println("Parent双参构造器"+name+":"+age);
	}
	public String toString(){
		return name+":"+age;
	}
	@Override
	public int compareTo(Parent o) {
		/*Parent p=(Parent)o;*/
		return this.age-o.getAge();
	}
	public int getAge(){
		return age;
	}
}
class Children extends Parent{
	public Children(String name, int age) {
		/*super(name, age);*/
		this.name=name;
		this.age=age;
	}
	protected String name;
	protected int age;
	public int compareTo(Parent o){
		Children c=(Children)o;
		return c.age-this.age;
	}
	public String toString(){
		return name+":"+age;
	}
}


Parent双参构造器P_lzz:45
Parent双参构造器P_lzh:47
Parent双参构造器P_bruce:24
Parent双参构造器P_Luce:22
Parent双参构造器Jame1:12
Parent双参构造器Jame2:23
Parent双参构造器Jame3:46
TreeSet遍历-------
Jame3:46
Jame2:23
Jame1:12
P_Luce:22
P_bruce:24
P_lzz:45
P_lzh:47

当子类重写了父类的CompareTo方法时各自使用对应的CompareTo方法,如果没有重写则调用父类的CompareTo方法,向TreeSet中加入子类时实际比对的是其父类的值。

class Children extends Parent{
	public Children(String name, int age) {
		/*super(name, age);*/
		this.name=name;
		this.age=age;
	}
	protected String name;
	protected int age;
	/*public int compareTo(Parent o){
		Children c=(Children)o;
		return c.age-this.age;
	}*/
	public String toString(){
		return name+":"+age;
	}
}

当子类构造器调用父类无参构造器并注释掉重写的CompareTo方法后输出入下:

Parent双参构造器P_lzz:45
Parent双参构造器P_lzh:47
Parent双参构造器P_bruce:24
Parent双参构造器P_Luce:22
Parent无参构造器null:0
Parent无参构造器null:0
Parent无参构造器null:0
TreeSet遍历-------
Jame2:23
P_Luce:22
P_bruce:24
P_lzz:45
P_lzh:47

由于父类年龄都是默认值0,因此只有第一个插入的子类被加到TreeSet中。



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值