java:String Arrays列表并删除
在这样的测试中:
@Test public void test() { List l = new LinkedList(); 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
来比较数组? 或者唯一的解决方案是将String数组包装在一个对象中并覆盖equals/hashcode
?
使用番石榴,有。 您需要实现Equivalence
:
public final class MyEquivalence extends Equivalence { @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
的.wrap()
方法插入/删除/ etc:
final Equivalence eq = new MyEquivalence(); list.add(eq.wrap(oneValue)); list.remove(eq.wrap(anotherValue));
使用番石榴。 在我之后重复。 使用番石榴:p
您正在创建一个新的Object引用并将其传递给remove()
方法。 从您发布的数据看,您可以创建一个具有两个属性的自定义类,并覆盖其equals()
和hashCode()
而不是将它们存储为String[]
或者保持对String[]
对象的引用并将其用于参考删除。
List
方法通常基于Object
方法equals(Object o)
,默认情况下比较对象的引用。 如果要稍后删除它,可以存储选项卡,或者创建自己的类并覆盖equals(Object o)
;)
@Test public void test() { List l = new LinkedList(); l.add(new String [] {"test", "123"}); String[] tab = new String [] {"test", "456"}; l.add(tab); l.add(new String [] {"test", "789"}); assertEquals(3, l.size()); l.remove(tab); assertEquals(2, l.size()); }
顺便说一句,Java 8引入了一个新的removeIf方法,该方法删除了满足给定谓词的此集合的所有元素
它可用于从列表中轻松删除字符串数组:
List l = new LinkedList(); l.add(new String [] {"test", "123"}); l.add(new String [] {"test", "456"}); l.add(new String [] {"test", "789"}); String[] newArray = new String[] {"test", "456"}; l.removeIf(array -> Arrays.equals(array, newArray));