user2001375
user2001375

Reputation: 89

Using a nested for loop to find duplicates

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;
}

Upvotes: 0

Views: 2979

Answers (1)

Kevin
Kevin

Reputation: 56059

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

Upvotes: 1

Related Questions