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
}
}
TreeSetis the way to go. You need aComparatorinstead.hashCode(), may save you more headaches in the future...finaland OP can't extend it. Another solution (based on your idea) would be creating a wrapper class for this unknown library class and override theequalsandhashCodefunctions (still, lot of boilerplate code to maintain).