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;
     }
    }

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

  • 相关阅读:
    C# 用Linq的方式实现对Xml文件的基本操作(创建xml文件、增删改查xml文件节点信息)
    Linq Like
    BS下实现WIN7下Aero效果
    Log4Net使用指南
    Sql 中取小数点后面两位小数.
    微软企业库回滚操作
    C#文件操作
    LinQ To XML——用LinQ查询XML
    Sql Server 字段类型说明
    Blog of the Day:几个中文技术类Blogger Groups
  • 原文地址:https://www.cnblogs.com/liyuanjinglyj/p/4656615.html
Copyright © 2011-2022 走看看