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 >(
コンパレータの使用)
:
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
}
}