前景提要
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 | 初学一级 | 园豆: 5
提问于:2019-03-20 21:28 显示帮助
使用"Ctrl+Enter"可进行快捷提交,评论支持部分 Markdown 语法:[link](http://example.com) _italic_ **bold** `code`。
< > 分享
分享您的问题
所有回答(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 编辑文本 预览 上传图片
Ctrl+Enter键快速提交 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,出来就是两个不同对象了啊! 别别别我拒绝 | 园豆:244 (菜鸟二级) | 2019-03-21 18:20 编辑文本 预览 上传图片
Ctrl+Enter键快速提交
清除回答草稿
您需要 登录 以后才能回答,未注册用户请先 注册 。