Ayush Goyal
Ayush Goyal

Reputation: 392

TreeSet Duplicates

I was trying to understand someones code.

public class Card  {
    String symbol;
    int no;

    public String getSymbol() {
        return symbol;
    }

    public void setSymbol(String symbol) {
        this.symbol = symbol;
    }
    public int getNo() {
        return no;
    }
    public void setNo(int no) {
        this.no = no;
    }

    public String toString(){
        return symbol+" "+no;
    }

}
class MyComparator1 implements Comparator<Card> {

    @Override
    public int compare(Card arg0, Card arg1) {

        return arg0.getSymbol().compareTo(arg1.getSymbol());
    }

}

public class Card2 {
public static void main(String[] args) {
    Card c2;        
    Scanner s = new Scanner(System.in);
    Set<Card> c = new TreeSet<Card>(new MyComparator1());
    while(c.size()<4) {
        System.out.println("Enter symbol and number");
        String symbol = s.next();
        int no = s.nextInt();
        c2 = new Card();
        c2.setSymbol(symbol);
        c2.setNo(no);
        c.add(c2);
    }
    Iterator<Card> it = c.iterator();
    {
        while (it.hasNext()) {
            Card c1 = it.next();
            System.out.println(c1.toString());
        }
    }
}
}

In this we are trying to display the different colour with respective number until we get 4 different color.

we are using treeset here. Example if we enter this input

a 1
b 2
c 2
b 4
d 2

output is

a 1
b 2
c 2
d 2

in this how Set recognize difference between b 2 & b 4? if we take map and use symbol as key then it is under standable but how set found similarity we are just passing Card object?

Upvotes: 2

Views: 249

Answers (1)

Eran
Eran

Reputation: 394146

The MyComparator1 instance you pass to the TreeSet's constructor determines which objects are considered to be unique. In your example, it's the symbol property that determines uniqueness.

It would make more sense though to use both symbol and no to determine uniqueness, since two cards having the same symbol but different number shouldn't be considered identical (for example b 2 & b 4 should not be considered identical).

Upvotes: 1

Related Questions