我有一组字符串[].我想检查这个Set是否包含另一个String [].
Set<String[]> s = new HashSet<String[]>();
s.add(new String[] {"lucy", "simon"});
System.out.println(s.contains(new String[] {"lucy", "simon"}));
Run Code Online (Sandbox Code Playgroud)
但是,打印为false.我猜这是因为只有引用被比较而不是实际的字符串.看来,我唯一的选择是创建一个类,比如Phrase,并实现hashCode()和equals()(使用Arrays.hashCode(...)).
有没有其他方法可以实现我想要的?
Ral*_*lph 13
你的猜测是正确的:arrays([])没有实现深度等于方法:如果它们是同一个实例,它们是相等的.
最简单的解决方案是:替换String[]为List<String>
另一种方式(但我不推荐它)是实现你自己的Set,它不是基于Object.equals但是基于java.util.Arrays.equals(Object[]a, Object[]b)
San*_*rma 11
转换String[]为List<String>,它应该很好.
Set<List<String>> s = new HashSet<List<String>>();
s.add(Arrays.asList("lucy", "simon"));
System.out.println(s.contains(Arrays.asList("lucy", "simon")));
Run Code Online (Sandbox Code Playgroud)