java:String Arrays列表并删除 [英] java: List of String Arrays and remove

查看:134
本文介绍了java:String Arrays列表并删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这样的测试中:

    @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的默认
有没有办法让列表能够使用 Arrays.equals / Arrays.hashcode 来比较数组?或者唯一的解决方案是将String数组包装在一个对象中并覆盖 equals / hashcode

the second assertion(=2) fails as the equals/hashcode used in list.remove are the default for Object. Is there a way to make the list able to use Arrays.equals/Arrays.hashcode to compare the arrays? Or the only solution is wrapping the String arrays in an object and overriding equals/hashcode?

推荐答案

使用番石榴,有。您需要实现 Equivalence< String []>

Using Guava, there is. You will need to implement an 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 插入/删除/ etc .wrap()方法:

You would then need to have your list being a List<Equivalence.Wrapper<String[]>>, and insert/remove/etc using your Equivalence's .wrap() method:

final Equivalence<String[]> eq = new MyEquivalence();
list.add(eq.wrap(oneValue));
list.remove(eq.wrap(anotherValue));

使用番石榴。在我之后重复。使用番石榴:p

Use Guava. Repeat after me. Use Guava :p

这篇关于java:String Arrays列表并删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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