将数组存储在 Set 中并避免重复

2022-01-17 00:00:00 arrays set hash java generics
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 数组的 Hash 方法.或者就此而言,一个通用数组?有没有更好的方法来完成我想做的事情?

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.hashCode() 实现,您无法覆盖它.不要在 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!

改为使用一组列表.

相关文章