在设置和避免重复存储阵列 [英] Storing arrays in Set and avoiding duplicates

查看:93
本文介绍了在设置和避免重复存储阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HashSet<String[]> boog = new HashSet<String[]>();
boog.add(new String[]{"a", "b", "c"});
boog.add(new String[]{"a", "b", "c"});
boog.add(new String[]{"a", "b", "d"});

结果

[a, b, c]
[a, b, d]
[a, b, c]

其中, [A,B,C] 是重复的,所以预期的哈希函数不能正常工作。我怎么会去重写哈希方法的String数组。或者,对于这个问题,一个通用的阵列?有没有更好的方式来完成我想要做什么?

where [a,b,c] is repeated, so the hash function is not working as expected. How would I go about overriding the Hash method for String arrays. Or for that matter, a generic array? Is there a better way to accomplish what I'm trying to do?

推荐答案

您不能。阵列使用基于身份的默认Object.hash code(),并且也没有办法,你可以覆盖。不要用数组作为键在HashMap / HashSet的!

You can't. arrays use the default identity-based Object.hashCode() implementation and there's no way you can override that. Don't use Arrays as keys in a HashMap / HashSet!

使用一组列表,而不是

这篇关于在设置和避免重复存储阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆