在这样的测试中:
@Test
public void test() {
List<String[]> l = new LinkedList<String[]>();
l.add(new String [] {"test", "123"});
l.add(new String [] {"test", "456"});
l.add(new String [] {"test", "789"});
assertEquals(3, l.size());
l.remove(new String [] {"test", "456"});
assertEquals(2, l.size());
}
第二个断言 (=2) 失败,因为 list.remove
中使用的 equals/hashcode
是 Object 的 default
。
有没有办法让列表能够使用 Arrays.equals/Arrays.hashcode
来比较数组?或者唯一的解决方案是将字符串数组包装在一个对象中并覆盖 equals/hashcode
?
最佳答案
使用 Guava ,有。您将需要实现 Equivalence<String[]>
:
public final class MyEquivalence
extends Equivalence<String[]>
{
@Override
protected boolean doEquivalent(final String[] a, final String[] b)
{
return Arrays.equals(a, b);
}
@Override
protected int doHash(final String[] t)
{
return Arrays.hashCode(t);
}
}
然后您需要将列表设为 List<Equivalence.Wrapper<String[]>>
,并使用您的 Equivalence
插入/删除/等的 .wrap()
方法:
final Equivalence<String[]> eq = new MyEquivalence();
list.add(eq.wrap(oneValue));
list.remove(eq.wrap(anotherValue));
使用 Guava 。跟着我重复。使用 Guava :p
关于java:字符串数组列表并删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17207301/