首页 新闻 会员 周边 捐助

java 要求完善Key类输出ABC,怎么做呢?一个面试题哦,重写了eques,hashcode都没有起作用

-1
悬赏园豆:5 [待解决问题]

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

}

renshen4322的主页 renshen4322 | 初学一级 | 园豆:5
提问于:2019-03-20 21:28
< >
分享
所有回答(2)
0

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

}

ydc886 | 园豆:202 (菜鸟二级) | 2019-03-21 10:40
0

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,出来就是两个不同对象了啊!

烟锁池塘柳12F | 园豆:244 (菜鸟二级) | 2019-03-21 18:20
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册