public class Key {
private byte[] bytes;
public Key(byte[] bytes) {
this.bytes = bytes;
}
public static void main(String[] args) {
HashMap<Key, String> map = new HashMap<>();
map.put(new Key(new byte[]{0x01, 0x02}), "ABC");
System.out.println(map.get(new byte[]{0x01, 0x02}));
}
}
public class Key {
private byte[] b;
public Key(final byte[] b) {
this.b = b;
}
public static void main(String[] args) {
//TODO auto generating..
final HashMap<Key, String> map = new HashMap<>();
map.put(new Key(new byte[] {0x01, 0x02}), "ABC");
System.out.println(map.get(new Key(new byte[] {0x01, 0x02})));
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Key key = (Key) o;
return Arrays.equals(b, key.b);
}
@Override
public int hashCode() {
return Arrays.hashCode(b);
}
}
public static void main(String[] args) {
HashMap<Key, String> map = new HashMap<>();
Key key = new Key(new byte[]{0x01, 0x02});
map.put(key, "ABC");
System.out.println(map.get(key));
}
这样不就可以了吗?
你两个里面都用new,出来就是两个不同对象了啊!