在java中创建一组数组 [英] Creating a Set of Arrays in java

查看:110
本文介绍了在java中创建一组数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做类似的事情

Set <String[]> strSet = new HashSet <String[]> ();

是否有一种简单的方法可以用Java创建一组数组,或者我是否必须编写代码自己实施?将对象添加到Set使用equals()检查Object,这对数组不起作用。

Is there an easy way to make a Set of arrays in Java, or do I have to code my own implementation? Adding an object to a Set checks the Object using equals(), which does not work for arrays.

推荐答案

数组不覆盖等于 hashCode ,因此 HashSet 将进行比较它们仅基于引用相等。请考虑使用 List

Arrays don't override equals and hashCode, and so the HashSet will compare them based on reference equality only. Consider using Lists instead:

Set<List<String>> strSet = new HashSet<List<String>>();

来自 List.equals 文档:


返回 true 当且仅当指定的对象也是列表时,两个列表的大小相同,以及两个列表中所有相应的元素对都是相等

Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal.

这篇关于在java中创建一组数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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