zoukankan      html  css  js  c++  java
  • 当key为自定义类时,TreeMap的使用及输出

    因为类本身并不知道怎么进行比较所以类要实现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;
     }
    }

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    boost::asio在VS2008下的编译错误
    Java集合框架——接口
    ACM POJ 3981 字符串替换(简单题)
    ACM HDU 1042 N!(高精度计算阶乘)
    OneTwoThree (Uva)
    ACM POJ 3979 分数加减法(水题)
    ACM HDU 4004 The Frog's Games(2011ACM大连赛区第四题)
    Hexadecimal View (2011ACM亚洲大连赛区现场赛D题)
    ACM HDU 4002 Find the maximum(2011年大连赛区网络赛第二题)
    ACM HDU 4001 To Miss Our Children Time (2011ACM大连赛区网络赛)
  • 原文地址:https://www.cnblogs.com/liyuanjinglyj/p/4656615.html
Copyright © 2011-2022 走看看