现在的位置: 首页 > 综合 > 正文

当key为自定义类时,TreeMap的使用及输出

2018年06月06日 ⁄ 综合 ⁄ 共 1779字 ⁄ 字号 评论关闭

因为类本身并不知道怎么进行比较所以类要实现comparable接口并且要覆写public int compareTo(Person o)此方法。而且还要覆写equals()和hashCode()方法。如果不覆写equals()方法那么即使对象对应值都相等,但地址内存不一样程序还是会输出重复项。

主程序

package liyuanjinglyj;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class MyMainToPerson {
 public static void main(String[] args) {
    Map map=new TreeMap();
    map.put(new Person("sssss",22), "jingying");
    map.put(new Person("bbbbb",23), "gaoshou");
    map.put(new Person("xxxxxxx",21), "dineng");
    System.out.println(map.get(new Person("sssss",22)));
    Set> set=map.entrySet();
    Iterator> iter=set.iterator();
    while(iter.hasNext()){
     Map.Entry mp=iter.next();
     System.out.println(mp.getKey()+"->>"+mp.getValue());
    }
//  Map  map=new HashMap();
//  map.put("zhangsan",1);
//  map.put("zhangsan",2);
//  map.put("liyuanjinglyj",3);
//  map.put("baoling",4);
//  for(Map.Entry me : map.entrySet()){
//   System.out.println(me.getKey()+"->>"+me.getValue());
//  }
  
//  Set> set=map.entrySet();
//  Iterator> iter=set.iterator();
//  while(iter.hasNext()){
//   Map.Entry mp=iter.next();
//   System.out.println(mp.getKey()+"->>"+mp.getValue());
//  }
    }
}
自定义类Perso

package liyuanjinglyj;

public class Person implements Comparable{
 String name;
 int age;
 public Person(String n,int a){
  this.name=n;
  this.age=a;
 }
 public int compareTo(Person o){
  if(this.age>o.age){
   return 1;
  }
  else if(this.age
   return -1;
  }
  else{
   return this.name.compareTo(o.name);
  }
 }
 public int hashCode() {
  return this.name.hashCode()*this.age;
 }
 public boolean equals(Object obj) {
  if(this==obj)
   return true;
  if(!(obj instanceof Person))
   return false;
  Person p=(Person)obj;
  if(this.name==p.name&&this.age==p.age){
   return true;
  }
  else{
   return false;
  }
 }
 public String toString(){
  return "姓名"+this.name+"年龄"+this.age;
 }
}

抱歉!评论已关闭.