TreeSet存储自定义对象

cannot be cast to java.lang.Comparable,遇到这个异常错误,就是说treeMap(或者treeSet)并不知道该如何put(add),就会报这个异常错误。


自定义的对象需要实现Comparable接口。


package com.anzy.set;

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

public class TreeSetDemo {

	public static void main(String[] args) {
		TreeSet  t = new TreeSet(); //放入treeset中的类必须实现Comparable接口
		t.add(new Pet("dog",2));
		t.add(new Pet("dog",3));
		t.add(new Pet("cat",3));
		Iterator it = t.iterator();
		while(it.hasNext()){
			Pet pet = (Pet) it.next();
			System.out.println(pet.getAge()+"  "+ pet.getName());
		}

	}

}

class Pet implements Comparable{
	private String name;
	private int age;
	
	public Pet(String name, int age) {
		this.age = age;
		this.name = name;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	@Override
	public int compareTo(Object o) {
		if(!(o instanceof Pet))
			throw new RuntimeException("不是pet");
		Pet p = (Pet) o;
		if(this.age>p.age)
			return 1;
		if(this.age == p.age){
			this.name.compareTo(p.name);//先按age排序然后按照name排序
		}
		return -1;
	}
	
}



版权声明:本文为qq_24549805原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。