The easiest way is to use a Set<Card>
. If the return value of adding an object to a set is false
, then it means the set already contains it, thus a duplicate. For this to work the Card
class must override both hashCode
and equals
.
Set<Card> set = new HashSet<>();
for(Card card : cardArray) {
if (!set.add(card)) { // if false then !false is true so signal duplicate.
System.out.println("Duplicate of " + card + " found);
break;
}
}
You can always sort the Cards and then do a one to one comparison to see if they are equal. Comparing adjacent cards of a sorted deck can also detect duplicates.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…