Treeset contains repeated elements

1

I am trying to keep an ordered list without repeated elements. I have created a TreeSet, but I see that it inserts repeated elements and I do not see clearly why. If I use TreeSet.contains () it does not detect it either. Here the code

TreeSet array = new TreeSet(new Comparator<Integer>(){
        @Override
        public int compare(Integer o1, Integer o2) {
            return o1>o2?o1:o2;
        }
    });
    int valor =0;
    for(int scores_i=0; scores_i < n; scores_i++){

        valor=in.nextInt();
        if (!array.contains(valor)){
            array.add(valor);
        }
    }

The values that I enter are 100,100,50,25

    
asked by Roberto Gimenez 30.06.2017 в 12:04
source

2 answers

2

The implementation of Comparator is wrong. From Javadoc

  

Returns:       a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

Since you only pass positive values, it always indicates that the first element is greater than the second, regardless of the values.

A typical implementation for ints would be

return o2-o1;

If o1 is less returns a number greater than 0, if o1 is greater returns a negative number, if both are equal returns 0 .

Of course, it is easier to use the compareTo of Integer method directly, since Integer implements Comparable

return o1.compareTo(o2);

or directly create a TreeSet without Comparator , since you use the order defined by Integer.compareTo and that already does TreeSet without needing more logic.

    
answered by 30.06.2017 / 12:16
source
-1

The comparator must return 1, 0 or -1.

1 if it is greater, 0 if it is equal and -1 if it is less.

You are comparing two numbers, and then you return one or the other depending on whether it is greater or not, if both numbers are positive, you will always return > 0 so he will always tell you that the first one is bigger.

Try something like this:

@Override
    public int compare(Integer o1, Integer o2) {
        int flag = 0;
        if(o1>o2){
            flag = 1;
        } else if(o1 == o2){
            flag = 0;
        } else {
            flag = -1;
        }
        return flag;
    }
    
answered by 30.06.2017 в 12:54