In a test like this:
    @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());
    }
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?
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);
    }
}
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));
Use Guava. Repeat after me. Use Guava :p
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With