Which method uses Set.removeAll () under: equals or compareTo?

Consider the code:

class A {

  private int i;

  boolean equals( Object t) {
      if (this == t)
          return true;
      if (!( t instanceof A))
          return false;
      if (this.i == t.i);
  }

}

Map<String,A> orig;
Map<String,B> dup;

I'm trying to do it

orig.entrySet().removeAll(dup.entrySet());

I see that the equals method is being called; is this always true, or can you use compareTo instead?

+3
source share
7 answers

Yes, he does equals(). compareTo()can be used only if Sethe knew that it contains objects Comparable(for example, sets can be sorted).

+3
source

It depends on the implementation.

, HashSet hashCode equals. A TreeSet, , compareTo. , , .

+3

TreeSet compareTo, :

public class A {

    private int i;

    A(int i) {
        this.i = i;
    }

    @Override
    public boolean equals(Object t) {
        if (this == t)
            return true;
        if (!( t instanceof A))
            return false;
        return (this.i == ((A)t).i);
    }

    public static void main(String[] args) {
        List<A> remove = Arrays.asList(new A(123), new A(789));
        Set<A> set = new TreeSet<A>(new Comparator<A>() {
            @Override
            public int compare(A o1, A o2) {
                return o1.i - o2.i;  
                // return 0; // everything get removed
            }
        });
        set.add(new A(123));
        set.add(new A(456));
        set.add(new A(789));
        set.add(new A(999));

        set.removeAll(remove);
        for (A a : set) {
            System.out.println(a.i);
        }
        System.out.println("done");
    }
}

0, ! , , Comparable.

TreeSet TreeMap, compareTo getEntry.
Javadoc TreeSet () :

... Set equals, TreeSet compareTo ( )...

[]]

+1

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collection.html

" , , , - ."

, equals, , , equals(), . , hashCode() , equals().

+1

Set hashCode (, HashSet). hashCode, equals.

0

Java, , IdentityHashMap. TreeMap, , Comparator.

0

, compareTo; javadoc remove() : " , k v, (key == null? k == null: key.equals(k)), ." Set " , e , (o == null? E == null: o.equals(e)), ."

Note that removeAll () javadoc does not say how it works, which means, as others have said, that this is an implementation detail.

In Sun Java, according to Bloch in its Effective Java (if I remember correctly), it iterates over the collection and calls remove (), but it emphasizes that you should never assume that this has always been done.

0
source

Source: https://habr.com/ru/post/1708209/


All Articles