不使用element.hashCode()的java.util.Set实现

时间:2013-02-23 21:56:33

标签: java collections set

是否有java.util.Set实现没有调用插入元素的hashCode()方法?

我必须使用某些库hashCode()实现不正常的类:当调用此hashCode()方法时,它会发送HTTP请求.......因此,放置一个实例将该类放入HashSet会导致触发HTTP请求 我希望尽量减少与此hashCode()方法的互动。因此,我需要一个Set实现,它不会利用其包含的元素的hashCode()方法。

1 个答案:

答案 0 :(得分:2)

查看Object.hashCode()方法和Set界面的文档。

使用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
   }
}

使用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
   }
}