0

I've been trying to write this code for a while now and I cannot figure out what is wrong with my nested for loop. I think it may be a problem with my if statement but I'm not sure. The code is supposed to search through ten random playing cards to find any duplicates. I know the rest of the code is working but I cannot figure out what I've done wrong with this part. If anyone could help I would be really grateful. (Java)

    /*
 * Return true if there is a duplicate card in the pack
 */
public boolean hasDuplicate() {
    for (int i = 0; i < pack.size(); i++){
        for (int j = i; j < pack.size(); j++) {
            if (i != j && pack.get(i).equals(pack.get(j))){
                pos = i;
                return true;
            } 
        }
    }
    return false;
}
19
  • 1
    Seems like ok to me. How exactly is it not working? What is pack? Commented Jan 22, 2013 at 18:40
  • 1
    Did you override .equals() on whatever's in the list? Commented Jan 22, 2013 at 18:43
  • @RohitJain, pack is the arraylist that it is searching through. It is not working as in when I test it, the answer always comes out as false. Commented Jan 22, 2013 at 18:43
  • @Kevin.. How is that going to matter? Commented Jan 22, 2013 at 18:44
  • 1
    I bet you not override equals in Card Commented Jan 22, 2013 at 18:52

1 Answer 1

1

The class you are using (Card) does not have an appropriately overridden .equals() method, so it is using the Object default - the equality operator (==) - to check whether two objects are equal. You are populating the array with a new object for each item in the array, so none of them are equal by ==, and therefore none of them are .equals(). You need to override its .equals() method to return whether the cards are semantically equal (i.e. same rank and suit). While you're at it, you should override hashCode as well, to maintain the general contract (if x.equals(y) then x.hashCode() == y.hashCode).

Sign up to request clarification or add additional context in comments.

1 Comment

Change the last line to: - You must also override hashCode method to maintain the contract between equals and hashCode.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.