java - Casting Comparator to work for a subclass -
in practice, safe following?
public static <t> comparator<t> downcast(final comparator<? super t> orig) { @suppresswarnings("unchecked") comparator<t> casted = (comparator<t>) orig; homecoming casted; }
here's contrived illustration of usage:
public static <t> comparator<t> chaincomparators(final comparator<? super t> a, final comparator<? super t> b) { if (a == null) { homecoming downcast(b); } if (b == null) { homecoming downcast(a); } homecoming new comparator<t>() { @override public int compare(t o1, t o2) { int = a.compare(o1, o2); if (i == 0) { = b.compare(o1, o2); } homecoming i; } }; } public static comparator<integer> odd_first_comparator = new comparator<integer>() { @override public int compare(integer i1, integer i2) { boolean iseven1 = (i1.intvalue() % 2) == 0; boolean iseven2 = (i2.intvalue() % 2) == 0; homecoming boolean.compare(iseven1, iseven2); } }; public static comparator<number> abs_number_comparator = new comparator<number>() { @override public int compare(number n1, number n2) { double d1 = math.abs(n1.doublevalue()); double d2 = math.abs(n2.doublevalue()); homecoming double.compare(d1, d2); } }; public static void main(string[] args) { comparator<integer> comp = null; comp = chaincomparators(comp, odd_first_comparator); comp = chaincomparators(comp, abs_number_comparator); list<integer> list = new arraylist<integer>(); list.add(-42); list.add(-23); list.add(-15); list.add(-4); list.add(8); list.add(16); collections.sort(list, comp); system.out.println(list); // prints [-15, -23, -4, 8, 16, -42] }
i know create chaincomparators()
homecoming comparator<? super t>
instead of using downcast()
, or alter of code not utilize or explicitly check null comparators (which removes need utilize downcast), neither of these changes seem worth effort big codebase. there reasonable situation either downcast()
or chaincomparators()
fail?
it should safe, because comparator
consumer, means instances of t
passed arguments, , never returned.
as far can see, code good.
java generics casting
No comments:
Post a Comment