在 Set 中存储数组并避免重复 [英] Storing arrays in Set and avoiding duplicates

查看:26
本文介绍了在 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 中存储数组并避免重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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