如何在这个TreeMap中实现equals和compare

时间:2014-03-23 11:00:49

标签: java collections treemap

如何在此树形图中实现可比较和等于方法,以便我的包含值返回true。

怎么做?

如何实施?

import java.util.*;
class a
{
    public static void main(String arr[])
    {
        TreeMap<String,Emp> map=new TreeMap<String,Emp>();
        map.put("HEllo",new Emp("ada",23));
        map.put("aehqn",new Emp("rewr",343));
        map.put("rffewrf",new Emp("saerfwe",893743));
        Set<Map.Entry<String,Emp>> x=map.entrySet(); 
        Iterator<Map.Entry<String,Emp>> itr =x.iterator();
        while(itr.hasNext())
        {
            Map.Entry<String,Emp> m=itr.next();
            System.out.println(m.getKey());
            Emp e=m.getValue();
            e.display();
            System.out.println();
        }
        System.out.println("NOw the value we will finid is"+map.containsValue(new Emp("ada",23)));
    }
}
class Emp
{
    String n;
    int i;
    public Emp(String n,int i)
    {
        this.n=n;
        this.i=i;
    }
    public void display()
    {
        System.out.println("there are string  "+n+"  int"+i);
    }
}

提前致谢

1 个答案:

答案 0 :(得分:1)

您的代码看起来像

class Emp implements Comparable<Emp>
{
    String n;
    int i;
    public Emp(String n,int i)
    {
        this.n=n;
        this.i=i;
    }
    public void display()
    {
        System.out.println("there are string  "+n+"  int"+i);
    }

    public boolean equals(Object o){
        if(o instanceof Emp){
            Emp d = (Emp)o;
            return ((d.n.equals(n)) && (d.i==i));
        }
        return false;
    }

    public int hashCode(){
        return i/2 + 17;
    }


    public int compareTo(Emp d){
        if(this.i>d.i)
            return 1;
        else if(this.i<d.i)
            return -1;
        return this.n.compareTo(d.n);
    }

}

如果出现语法错误,请忽略,您也可以改进方法实现。