import java.util.*;
public class Person implements Comparable<Person>//使Person的属性具有比较性
{
PRivate String name;
private int age;
public Person(String name,int age)//初始化构造函数
{
this.name = name;
this.age = age;
}
public void set(String name,int age)//重新设置姓名和年龄
{
this.name = name;
this.age = age;
}
public String getName()//获取姓名
{
return name;
}
public int getAge()//获取年龄
{
return age;
}
public String toString()//将姓名和年龄以字符串的形式返回
{
returnname+","+age;
}
//出现重名时,再找到另一个hash地址用来存储数据(底层自动调用)
publicinthashCode()
{
returnname.hashCode()+age*34;
}
//判断接受的类是不是Person类,不是就抛出异常(底层自动调用)
publicbooleanequals(Object obj)
{
if(!(objinstanceofPerson))
thrownew ClassCastException("不是Person类");
Person p = (Person)obj;
returnthis.name.equals(p.name) &&this.age==p.age;
}
public int compareTo(Person p)//(按照自己的要求去作比较)
{
int num=new Integer(this.age).compareTo(p.age);
return num==0?this.name.compareTo(p.name):num;
}
}
public class Test
{
public static <T>void sop(T t)
{
System.out.println(t);
}
public static void main(String args[]) throws Exception
{
//创建一个map集合,用来存储数据 <>表示接收的是泛型,即指定的类型
TreeMap<Person,String> map = new TreeMap<Person,String>(/*new Mycompare()*/);
//往集合添加数据
map.put(new Person("czhangsan1",11),"beijing");
map.put(newPerson("zhangsan5",15),"nanjing");
map.put(newPerson("azhangsan5",10),"shanghai");
map.put(newPerson("zhangsan2",20),"haierbing");
map.put(newPerson("bzhangsan2",20),"beijing");
map.put(newPerson("zhangsan3",12),"shanghai");
map.put(newPerson("zhangsan4",19),"changchun");
map.put(newPerson("zhangsan4",10),"changchun");
map.put(new Person("zhangsan4",10),"zhengzhou");
//将map集合转换为set集合,因为map集合没有迭代器 ,而set集合有
Set<Map.Entry<Person,String>> entryset = map.entrySet();
//获取迭代器
Iterator<Map.Entry<Person,String>> it = entryset.iterator();
//用迭代器取数据
while(it.hasNext())
{
Map.Entry<Person,String> m = it.next();
Person key = m.getKey();//取出键
String value =m.getValue();//取出值
sop(key+"......."+"adress:"+value);//打印键和值
}
}
}
class Mycompare implements comparator<Perosn>//自定义一个比较器
{
public int compare(Person p1,Person p2)
{
int num = p1.getName().compareTo(p2.getName());
return num==0?new Integer(p1.getAge()).compareTo(new Integer(p2.getAge())):num;
}
}
//注意:上面的两种形式都实现了比较,任选其中一种就可以。要么实现comparable接口;要么在集合中传入自定义的比较器。
新闻热点
疑难解答