java 集合 TreeMap 键是对象,TreeMap中要重写compareTo方法


import java.util.TreeMap;

//键是对象,TreeMap中要重写compareTo(对应着要重写toString方法)方法,否则会出现异常;
public class TreeMapdemo 
{
public static void main(String[] args) 
{
TreeMap map = new TreeMap();  //声明Map对象;
map.put(new Hero("a", 22), "1");//增加元素;
map.put(new Hero("c", 34), "2");
map.put(new Hero("b", 24), "3");
System.out.println(map); //输出内容;
System.out.println(map.firstEntry());  //输出一个元素;
}
}


class Hero implements Comparable  //实现Comparable接口; 
{
String name;
Integer age;

public Hero(String name, Integer age)
{
this.name = name;
this.age = age;
}

@Override
public String toString()   //重写toString方法;
{
return "name=" + this.name + "  age=" + this.age + "  String";
}


@Override
public int compareTo(Hero h) //重写compareTo方法;
{
int num = 0;
int s = this.name.compareTo(h.name);
if(s>0)
{
num = 1;
}
else if(s<0)
{
num = -1;
}
else
{
num = this.age>h.age?1:(this.age==h.age?0:-1);
}
return num;
}

}

























你可能感兴趣的:(Java)