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.
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
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