Storing arrays in Set and avoiding duplicates(将数组存储在 Set 中并避免重复)
问题描述
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!
改为使用一组列表.
这篇关于将数组存储在 Set 中并避免重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将数组存储在 Set 中并避免重复


基础教程推荐
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 从 python 访问 JVM 2022-01-01