java - Sorting a List<Number> -
how sort list<number>
?
example:
list<number> li = new arraylist<number>(); //list of numbers li.add(new integer(20)); li.add(new double(12.2)); li.add(new float(1.2));
collections.sort(li,new comparator<number>() { @override public int compare(number o1, number o2) { double d1 = (o1 == null) ? double.positive_infinity : o1.doublevalue(); double d2 = (o2 == null) ? double.positive_infinity : o2.doublevalue(); return d1.compareto(d2); } });
have @ andreas_d's answer explanation.in above code null values , +infinity values handled such move end.
update 1:
as jarnbjo , aioobe points out flaw in above implementation.so thought it's better restrict implementation's of number.
collections.sort(li, new comparator<number>() { hashset<class<? extends number>> allowedtypes; { allowedtypes = new hashset<class<? extends number>>(); allowedtypes.add(integer.class); allowedtypes.add(double.class); allowedtypes.add(float.class); allowedtypes.add(short.class); allowedtypes.add(byte.class); } @override public int compare(number o1, number o2) { double d1 = (o1 == null) ? double.positive_infinity : o1.doublevalue(); double d2 = (o2 == null) ? double.positive_infinity : o2.doublevalue(); if (o1 != null && o2 != null) { if (!(allowedtypes.contains(o1.getclass()) && allowedtypes.contains(o2.getclass()))) { throw new unsupportedoperationexception("allowed types:" + allowedtypes); } } return d1.compareto(d2); } });
update 2:
using guava's constrained list (will not allow entry of null or unsupported type list):
list<number> li = constraints.constrainedlist(new arraylist<number>(), new constraint<number>() { hashset<class<? extends number>> allowedtypes; { allowedtypes = new hashset<class<? extends number>>(); allowedtypes.add(integer.class); allowedtypes.add(double.class); allowedtypes.add(float.class); allowedtypes.add(short.class); allowedtypes.add(byte.class); } @override public number checkelement(number arg0) { if (arg0 != null) { if (allowedtypes.contains(arg0.getclass())) { return arg0; } } throw new illegalargumentexception("type not allowed"); } } ); li.add(double.positive_infinity); li.add(new integer(20)); li.add(new double(12.2)); li.add(new float(1.2)); li.add(double.negative_infinity); li.add(float.negative_infinity); // li.add(null); //throws exception // li.add(new biginteger("22"); //throws exception li.add(new integer(20)); system.out.println(li); collections.sort(li, new comparator<number>() { @override public int compare(number o1, number o2) { double d1 = o1.doublevalue(); double d2 = o2.doublevalue(); return d1.compareto(d2); } }); system.out.println(li);
Comments
Post a Comment