Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which method does Set.removeAll() use underneath: equals or compareTo?

Tags:

java

set

map

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 am trying to do this

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

I see that the equals method is called; is this always true, or might it call compareTo instead?

like image 217
kal Avatar asked Jan 24 '23 15:01

kal


2 Answers

Yes, it calls equals(). compareTo() could only be used if the Set knew that it contained Comparable objects (sorted sets, for instance, might possibly do this).

like image 97
Michael Myers Avatar answered Feb 16 '23 02:02

Michael Myers


It depends on the implementation.

For instance, a HashSet will use hashCode and equals. A TreeSet will probably use compareTo. Ultimately, so long as your types behave appropriately it shouldn't matter.

like image 28
Jon Skeet Avatar answered Feb 16 '23 01:02

Jon Skeet