使用两个(或更多)对象作为HashMap键

Gam*_*ler 12 java hash map

我想将某些对象存储在HashMap中.问题是,通常你只使用一个对象作为密钥.(例如,您可以使用String.)我想要使用多个对象.例如,Class和String.有没有一种简单而干净的方法来实现它?

Pie*_*rre 14

你的密钥必须实现hashCode和equals.如果它是SortedMap,它还必须实现Comparable接口

public class MyKey implements Comparable<MyKey>
{
private Integer i;
private String s;
public MyKey(Integer i,String s)
{
this.i=i;
this.s=s;
}

public Integer getI() { return i;}
public String getS() { return s;}

@Override
public int hashcode()
{
return i.hashcode()+31*s.hashcode();
}

@Override
public boolean equals(Object o)
{
if(o==this) return true;
if(o==null || !(o instanceof MyKey)) return false;
MyKey cp= MyKey.class.cast(o);
return i.equals(cp.i) && s.equals(cp.s);
    }

   public int compareTo(MyKey cp)
     {
     if(cp==this) return 0;
     int i= i.compareTo(cp.i);
     if(i!=0) return i;
     return s.compareTo(cp.s);
     }


 @Override
    public String toString()
       {
       return "("+i+";"+s+")";
       }

    }

public Map<MyKey,String> map= new HashMap<MyKey,String>();
map.put(new MyKey(1,"Hello"),"world");
Run Code Online (Sandbox Code Playgroud)


ILM*_*tan 10

我倾向于使用列表

map.put(Arrays.asList(keyClass, keyString), value)
Run Code Online (Sandbox Code Playgroud)

  • 容易做到,但它的缺点是不记录列表中的内容.是吧,字符串; 还是字符串?还是classname和string? (2认同)