From bfe3ef5096d2deef1732f3b2c71b1cd107e55070 Mon Sep 17 00:00:00 2001 From: "ray.j.greenwell" Date: Fri, 4 Dec 2009 23:59:42 +0000 Subject: [PATCH] I may fiddle around with this, but here's one that works. Provide a method for getting a Comparable Comparator in a typesafe way. I had to change the Comparator to be untyped. Hopefully this doesn't hork anything. Oh, now I worry... git-svn-id: https://samskivert.googlecode.com/svn/trunk@2664 6335cc39-0255-0410-8fd6-9bcaacd3b74c --- src/java/com/samskivert/util/Comparators.java | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/java/com/samskivert/util/Comparators.java b/src/java/com/samskivert/util/Comparators.java index eb59ddb0..d0eaca69 100644 --- a/src/java/com/samskivert/util/Comparators.java +++ b/src/java/com/samskivert/util/Comparators.java @@ -49,7 +49,7 @@ public class Comparators /** * A comparator that compares {@link Comparable} instances. */ - public static final Comparator COMPARABLE = new Comparator() { + public static final Comparator COMPARABLE = new Comparator() { @SuppressWarnings("unchecked") public int compare (Object o1, Object o2) { @@ -60,10 +60,24 @@ public class Comparators } else if (o2 == null) { return -1; } - return ((Comparable)o1).compareTo(o2); // null-free + return ((Comparable)o1).compareTo(o2); // null-free } }; + /** + * Returns the Comparator for Comparables, properly cast. + * + *

This example illustates the type-safe way to obtain a natural-ordering Comparator: + *

+     *    Comparator<Integer> = Comparators.comparable();
+     * 
+ */ + @SuppressWarnings("unchecked") + public static final Comparator comparable () + { + return (Comparator) COMPARABLE; + } + /** * Compares two bytes, returning 1, 0, or -1. * TODO: remove when Java finally has this method in Byte.