Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: List of String Arrays and remove

Tags:

java

list

junit

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?

like image 536
Randomize Avatar asked Jun 20 '13 07:06

Randomize


1 Answers

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

like image 176
fge Avatar answered Oct 21 '22 00:10

fge