Abdull
Abdull

Reputation: 27812

java.util.Set implementation that does not use element.hashCode()

Is there a java.util.Set implementation that does not call an inserted element's hashCode() method?

I have to use some library's class whose hashCode() implementation is ill-behaving: when this hashCode() method is called, it sends an HTTP request....... therefore, putting an instance of that class into a HashSet causes a HTTP request to fire.
I want to reduce interactions with this hashCode() method to a minimum. Therefore, I need a Set implementation that does not exploit its contained element's hashCode() method.

Upvotes: 3

Views: 800

Answers (1)

Aubin
Aubin

Reputation: 14853

Take a look at the documentation of Object.hashCode() method and Set interface.

Using TreeSet< Comparable > :

import java.util.Set;
import java.util.TreeSet;

public class NoHashCode implements Comparable< NoHashCode >{

   final int value;

   public NoHashCode( int val ) {
      this.value = val;
   }

   @Override public int hashCode() {
      throw new IllegalStateException( "This method must not be called" );
   }

   @Override
   public int compareTo( NoHashCode o ) {
      return this.value - o.value;
   }

   public static void main( String[] args ) {
      Set< NoHashCode > set = new TreeSet<>();
      set.add(  new NoHashCode( 1 ));
      set.add(  new NoHashCode( 2 ));
      set.add(  new NoHashCode( 3 ));
      set.add(  new NoHashCode( 1 )); // '1' is already in set
      System.out.println( set.size());// print 3
   }
}

Using TreeSet< T >(comparator) :

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

public class NoHashCode {

   final int value;

   public NoHashCode( int val ) {
      this.value = val;
   }

   @Override public int hashCode() {
      throw new IllegalStateException( "This method must not be called" );
   }

   public static void main( String[] args ) {
      Set< NoHashCode > set = new TreeSet<>( new Comparator< NoHashCode >(){
         @Override public int compare( NoHashCode left, NoHashCode right ) {
            return left.value - right.value;
         }});
      set.add(  new NoHashCode( 1 ));
      set.add(  new NoHashCode( 2 ));
      set.add(  new NoHashCode( 3 ));
      set.add(  new NoHashCode( 1 )); // '1' is already in set
      System.out.println( set.size());// print 3
   }
}

Upvotes: 2

Related Questions