Java ArrayList: contains() method returns false when arraylist contains the given object

arraylist, arrays, contains, evaluation, java

Solution

The `hashCode()` and `equals()` of arrays are a bit broken when it comes to this (it is a long different discussion why).

A possible work around is to use `ArrayList<ArrayList<String>>` instead of `ArrayList<String[]>`, the `equals()` method for `ArrayList` will be as you expect it to.

For example:

    ArrayList<String> l1 = new ArrayList<>();
    ArrayList<String> l2 = new ArrayList<>();
    l1.add("asdf");
    l2.add("asdf");
    ArrayList<ArrayList<String>> coll = new ArrayList<>();
    coll.add(l1);
    System.out.println(coll.contains(l2));

Will yield `true`, as expected

Problem

I have a problem with the `contains()` method which returns false even though the `ArrayList` contains the given `Object`. My code is following: ``` String [] transaction = dbConnection.getPendingTransaction(username); if (!onlineConnection.getSentTransactionRequests().contains(transaction)) { onlineConnection.getSentTransactionRequests().add(transaction); String packet = "RTR" + "_" + transaction[0] + "_" + transaction[2] + "_" + transaction[3] + "_" + transaction[4]; onlineConnection.send(packet); } ``` I have tried `Thread.sleep()` between iterations, so the `ArrayList` wasn't load as eagerly without success.

Original source

Related problems