Skip to content

@v6ak /NaturalComparator.java
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
example of a reasonable Singleton
package v6ak.util;
import java.util.Comparator;
public final class NaturalComparator {
private static final Comparator<? extends Comparable<?>> instance = new Comparator<Comparable<Object>>(){
public int compare(Comparable<Object> o1, Comparable<Object> o2) {
if( o1==null || o2==null ){
throw new NullPointerException("Comparing null values is not supported!");
}
return o1.compareTo(o2);
}
};
@SuppressWarnings("unchecked")
public static <T extends Comparable<?>> Comparator<T> getInstance(){
return (Comparator<T>) instance;
}
private NaturalComparator(){}
}
package v6ak.util
import java.util.Comparator
object NaturalComparator extends Comparator[Comparable[Any]]{
def apply[T]() = asInstanceOf[Comparator[T]]
override def compare(o1:Comparable[Any], o2:Comparable[Any]) = {
if( o1 == null || o2 == null ){
throw new NullPointerException("Comparing null values is not supported!")
}
o1 compareTo o2
}
}
import v6ak.util.NaturalComparator
import java.util.Comparator
import java.lang.Integer
def compareChars(a:Char, b:Char, cmp: Comparator[Char]){
println(cmp.compare(a, b))
}
val intCmp = NaturalComparator[Integer]
val strCmp = NaturalComparator[String]
val universalCmp = NaturalComparator
val universalCmp2 = NaturalComparator()
println(intCmp.compare(Integer valueOf 1, Integer valueOf 2))
println(strCmp.compare("b", "a"))
println(intCmp eq strCmp) // intCmp and strCmp are the same, but they are casted to a different type
// Following two commented commands can't be compiled, of course. It does not make sense.
// println(universalCmp.compare("b", Integer valueOf 5)) // String would have to be able to compare itself with anything.
// println(universalCmp2.compare("b", Integer valueOf 5)) // There is not enough type info provided, so it can't be used.
// Following two commented commands can't be compiled. They make sense, but type information is too restrictive.
// println(universalCmp2.compare("a", "b"))
// println(universalCmp.compare("a", "b"))
compareChars('r', 'r', NaturalComparator()) // The type of comparator is inferred. However, it is neccessary to add braaces.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.