I've been trying to convert an Integer Wrapper class to int primitive class. I haven't yet found a proper way to make the code compile. I'm using Intellij IDEA, Java 11 Amazon Coretto, but I need to run it on a computer that runs java 8.
Here's the original code below:
static class Line<Integer> extends ArrayList<Integer> implements Comparable<Line<Integer>> {
#Override
public int compareTo(Line<Integer> other) {
int len = Math.min(this.size(), other.size());
for (int i = 0; i < len; i++) {;
if ((int) this.get(i) != (int) other.get(i)) {
if ((int this.get(i) < (int) this.get(i)) {
return -1;
} else if ((int) this.get(i) > (int)this.get(i)) {
return 1;
} else {}
}
}
...
note that the Line is inserted to an ArrayList.
Originally I used forced casting on all the Integer objects so it'll be like (int) this.get(i). It worked on my local terminal and my Intellij wasn't bothered about it, but unfortunately not the other computer. It couldn't compile there
I thought it was because of the forced casting, since the other computer returned
Main.java:159: error: incompatible types: Integer cannot be converted to int
if ((int) this.get(i) != (int) other.get(i)) {
^
where Integer is a type-variable:
Integer extends Object declared in class Line
so I deleted them all and thought I could let the machine unbox the Integer wrapper on its own. It still didn't compile.
If the code is left like what's written above (no forced casting), it will return "Operator '<' not applicable for 'Integer', 'Integer'"
So I used the .compareTo() method. Compile error.
Then I tried to assign them to an int variable. Intellij IDEA was screaming at me that it required int but found Integer instead. So I force-casted, like so
int thisLine = (int) this.get(i);
int otherLine = (int) other.get(i);
if (thisLine != otherLine) {
if (thisLine < otherLine) {
return -1;
} else if (thisLine > otherLine) {
return 1;
} else {}
Nope, didn't work. Removing the cast also didn't work.
I looked up the Javadocs (https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#intValue--) this time about the Integer class and found a promising little method called intValue(). Problem is? Intellij cannot resolve that method (oddly, VSCode does not consider this an error). I used it like this
int thisLine = this.get(i).intValue();
int otherLine = other.get(i).intValue();
if (this.get(i) != other.get(i)) {
if (thisLine < otherLine) {
return -1;
} else if (thisLine > otherLine) {
return 1;
and sure enough, another compile error on that stubborn computer.
I'm running out of options. I'm seriously considering creating a new custom class just so I can store int values in an ArrayList without having to deal with all this Java backwards incompatibility nonsense.
Anyone here know a consistent method for converting an Integer wrapper object to an int primitive object in Java?
This is the clue in the error message that explains it:
where Integer is a type-variable:
Integer extends Object declared in class Line
Integer is not java.lang.Integer but a type variable with a confusing name...
You declared the type variable here:
static class Line<Integer> extends ArrayList<Integer> implements Comparable<Line<Integer>>
It's as if you declared it like this:
static class Line<T> extends ArrayList<T> implements Comparable<Line<T>>
but by naming the type variable Integer instead of T, and then you try to cast objects of the type T to int later on.
Fix it by not declaring a type parameter named Integer, you don't need that here:
static class Line extends ArrayList<Integer> implements Comparable<Line<Integer>>
You shouldn't have to cast an Integer to an int at all. Integer class has .compareTo methods which compare two integers.
A 0 means value1 is equal to value2. -1 is value1 is less than value2 and a 1 is value1 is greater than value2.
Try the following:
public int compareTo(Line<Integer> other) {
//get the smallest length
int len = this.size() <= other.size() ? this.size() : other.size();
for (int i = 0; i < len; i++) {
int compare = this.get(i).compareTo(other.get(i));
if (compare != 0) { //if compare is not zero they are not the same value
return compare;
}
}
//If we get here, everything in both lists are the same up to "len"
return 0;
}
The compareTo() method is a method of Integer class under java. lang
package. ... It returns the result of the value 0 if Integer is equal
to the argument Integer, a value less than 0 if Integer is less than
the argument Integer and a value greater than 0 if Integer is greater
than the argument Integer.
In you class "Integer" is not a java.lang.Integer but a Generic class that is the reason
I want to define a generic class ComparableList<> that extend ArrayList and implements Comparable interfaces, such that two objects of type ComparableList can be compared using the compareTo method. The compareTo should perform a lexicographic comparison.
Here's my code:
class ComparableList <T extends Comparable<T>> extends ArrayList implements Comparable<ComparableList>{
#Override
public int compareTo(ComparableList o){
Iterator citer = this.iterator();
Iterator oiter = o.iterator();
while (citer.hasNext() && oiter.hasNext()){
if (citer.next() > oiter.next()){
return 1;
}else if (citer.next() < oiter.next()){
return -1;
}else {
if (!citer.hasNext()){
return -1;
}
if(!oiter.hasNext()){
return 1;
}
}
}
return 0;
}
}
and I got error messages like this:
TCL.java:11: error: bad operand types for binary operator '>'
if (citer.next() > oiter.next()){
^
first type: Object
second type: Object
TCL.java:13: error: bad operand types for binary operator '<'
}else if (citer.next() < oiter.next()){
^
first type: Object
second type: Object
I thought it should be a ComparableList but not an Object. Can anyone tell me the reason?
You need to compare the objects using Comparable.comapreTo() (that's why you have <T extends Comparable<T> there). You need to first check for nulls on either side.
Also, each call to Iterator.next() iterates to next element, you don't want to call it twice in one loop iteration - store the items at the loop start then use the stored values.
Comparable doesn't override the > and < operators (nothing can). Since your T implements Comparable, use compareTo:
int result = citer.next().compareTo(oiter.next());
if (result != 0) {
return result;
} else {
if (citer.hasNext()) {
return -1;
}
if (oiter.hasNext()) {
return 1;
}
}
Note that that also calls next only once per iteration, since next advanced the iterator.
Each element in your ComparableList is of type T extends Comparable<T>, for sure the binary operator is not available for it (Java doesn't have operator overloading), but since it extends Comparable, you have compareTo to be used as replacement for < and >. Use it instead.
I want to generate a binary tree with key - value pairs in their nodes.
In my binary tree I want to implement nodes at the beginning with an insert method, which implements a new left node if the key is smaller than the key of the current node. Then if there is already a left node it will check again for it. The same logic follows for right/greater node inserts.
I wrote my code first using the int type because it's way easier for me to test my code before I use generics (new topic for me). It worked when using int but I an unsure how to compare two generics with themselves by using "<" or ">".
public ListCell<Type> checkKey(Type key, ListCell<Type> checkCell) {
ListCell<Type> newCell = null;
if (key < checkCell.key && checkCell.left != null) {
...
}
...
}
I don't know if it's worth saying but I'm creating my binary tree with a selfcoded list.
Above you can see my current checks but i can't compare my given key now with checkCell.key because of them not being numbers.
So my general question is how to compare the keys in generics if they are "smaller" or "greater" than the other for my implementation in a binary tree.
Thanks in advance
You would need to ensure that your generic type implemented the Comparable interface, and then use the compareTo method instead. Java does not support overloading the > operator (or any operator overloading, for that matter).
As per the documents, compareTo:
Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
An example (that you'll have to map on to your exact code), assuming that key is your item you will store in your node, and checkCell.key is your node
int compareResult = key.compareTo(checkCell.key);
if (key < 0) { // it goes on the left }
else if (key == 0) { // it is the same }
else { // it goes on the right }
In your compareTo method you need to decide what fields in your class determine it's "ordering". For example, if you have a size and priority field, you might do:
#Override public int compareTo(Type other) {
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
if (this == other) return EQUAL;
if (this.size < other.size) return BEFORE;
else if (this.size > other.size) return AFTER;
else { // size is equal, so test priority
if (this.priority < other.priority) return BEFORE;
else if (this.priority > other.priority) return AFTER;
}
return EQUAL;
}
Bounded type parameters are key to the implementation of generic algorithms. Consider the following method that counts the number of elements in an array T[] that are greater than a specified element elem.
public static <T> int countGreaterThan(T[] anArray, T elem) {
int count = 0;
for (T e : anArray)
if (e > elem) // compiler error
++count;
return count;
}
The implementation of the method is straightforward, but it does not compile because the greater than operator (>) applies only to primitive types such as short, int, double, long, float, byte, and char. You cannot use the > operator to compare objects. To fix the problem, use a type parameter bounded by the Comparable<T> interface:
public interface Comparable<T> {
public int compareTo(T o);
}
The resulting code will be:
public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {
int count = 0;
for (T e : anArray)
if (e.compareTo(elem) > 0)
++count;
return count;
}
bounded type parameters
I want to compare to variables, both of type T extends Number. Now I want to know which of the two variables is greater than the other or equal. Unfortunately I don't know the exact type yet, I only know that it will be a subtype of java.lang.Number. How can I do that?
EDIT: I tried another workaround using TreeSets, which actually worked with natural ordering (of course it works, all subclasses of Number implement Comparable except for AtomicInteger and AtomicLong). Thus I'll lose duplicate values. When using Lists, Collection.sort() will not accept my list due to bound mismatchs. Very unsatisfactory.
This should work for all classes that extend Number, and are Comparable to themselves. By adding the & Comparable you allow to remove all the type checks and provides runtime type checks and error throwing for free when compared to Sarmun answer.
class NumberComparator<T extends Number & Comparable> implements Comparator<T> {
public int compare( T a, T b ) throws ClassCastException {
return a.compareTo( b );
}
}
A working (but brittle) solution is something like this:
class NumberComparator implements Comparator<Number> {
public int compare(Number a, Number b){
return new BigDecimal(a.toString()).compareTo(new BigDecimal(b.toString()));
}
}
It's still not great, though, since it counts on toString returning a value parsable by BigDecimal (which the standard Java Number classes do, but which the Number contract doesn't demand).
Edit, seven years later: As pointed out in the comments, there are (at least?) three special cases toString can produce that you need to take into regard:
Infinity, which is greater than everything, except itself to which it is equal
-Infinity, which is less than everything, except itself to which it is equal
NaN, which is extremely hairy/impossible to compare since all comparisons with NaN result in false, including checking equality with itself.
After having asked a similar question and studying the answers here, I came up with the following. I think it is more efficient and more robust than the solution given by gustafc:
public int compare(Number x, Number y) {
if (isSpecial(x) || isSpecial(y))
return Double.compare(x.doubleValue(), y.doubleValue());
else
return toBigDecimal(x).compareTo(toBigDecimal(y));
}
private static boolean isSpecial(Number x) {
var specialDouble = x instanceof Double d
&& (Double.isNaN(d) || Double.isInfinite(d));
var specialFloat = x instanceof Float f
&& (Float.isNaN(f) || Float.isInfinite(f));
return specialDouble || specialFloat;
}
private static BigDecimal toBigDecimal(Number number) {
if (number instanceof BigDecimal d)
return d;
if (number instanceof BigInteger i)
return new BigDecimal(i);
if (number instanceof Byte || number instanceof Short
|| number instanceof Integer || number instanceof Long)
return new BigDecimal(number.longValue());
if (number instanceof Float || number instanceof Double)
return new BigDecimal(number.doubleValue());
try {
return new BigDecimal(number.toString());
} catch(NumberFormatException e) {
throw new RuntimeException("The given number (\"" + number + "\" of class " + number.getClass().getName() + ") does not have a parsable string representation", e);
}
}
One solution that might work for you is to work not with T extends Number but with T extends Number & Comparable. This type means: "T can only be set to types that implements both the interfaces."
That allows you to write code that works with all comparable numbers. Statically typed and elegant.
This is the same solution that BennyBoy proposes, but it works with all kinds of methods, not only with comparator classes.
public static <T extends Number & Comparable<T>> void compfunc(T n1, T n2) {
if (n1.compareTo(n2) > 0) System.out.println("n1 is bigger");
}
public void test() {
compfunc(2, 1); // Works with Integer.
compfunc(2.0, 1.0); // And all other types that are subtypes of both Number and Comparable.
compfunc(2, 1.0); // Compilation error! Different types.
compfunc(new AtomicInteger(1), new AtomicInteger(2)); // Compilation error! Not subtype of Comparable
}
The most "generic" Java primitive number is double, so using simply
a.doubleValue() > b.doubleValue()
should be enough in most cases, but... there are subtle issues here when converting numbers to double. For example the following is possible with BigInteger:
BigInteger a = new BigInteger("9999999999999992");
BigInteger b = new BigInteger("9999999999999991");
System.out.println(a.doubleValue() > b.doubleValue());
System.out.println(a.doubleValue() == b.doubleValue());
results in:
false
true
Although I expect this to be very extreme case this is possible. And no - there is no generic 100% accurate way. Number interface have no method like exactValue() converting to some type able to represent number in perfect way without loosing any information.
Actually having such perfect numbers is impossible in general - for example representing number Pi is impossible using any arithmetic using finite space.
What about this one? Definitely not nice, but it deals with all necessary cases mentioned.
public class SimpleNumberComparator implements Comparator<Number>
{
#Override
public int compare(Number o1, Number o2)
{
if(o1 instanceof Short && o2 instanceof Short)
{
return ((Short) o1).compareTo((Short) o2);
}
else if(o1 instanceof Long && o2 instanceof Long)
{
return ((Long) o1).compareTo((Long) o2);
}
else if(o1 instanceof Integer && o2 instanceof Integer)
{
return ((Integer) o1).compareTo((Integer) o2);
}
else if(o1 instanceof Float && o2 instanceof Float)
{
return ((Float) o1).compareTo((Float) o2);
}
else if(o1 instanceof Double && o2 instanceof Double)
{
return ((Double) o1).compareTo((Double) o2);
}
else if(o1 instanceof Byte && o2 instanceof Byte)
{
return ((Byte) o1).compareTo((Byte) o2);
}
else if(o1 instanceof BigInteger && o2 instanceof BigInteger)
{
return ((BigInteger) o1).compareTo((BigInteger) o2);
}
else if(o1 instanceof BigDecimal && o2 instanceof BigDecimal)
{
return ((BigDecimal) o1).compareTo((BigDecimal) o2);
}
else
{
throw new RuntimeException("Ooopps!");
}
}
}
This should work for all classes that extend Number, and are Comparable to themselves.
class NumberComparator<T extends Number> implements Comparator<T> {
public int compare(T a, T b){
if (a instanceof Comparable)
if (a.getClass().equals(b.getClass()))
return ((Comparable<T>)a).compareTo(b);
throw new UnsupportedOperationException();
}
}
if(yourNumber instanceof Double) {
boolean greaterThanOtherNumber = yourNumber.doubleValue() > otherNumber.doubleValue();
// [...]
}
Note: The instanceof check isn't necessarily needed - depends on how exactly you want to compare them. You could of course simply always use .doubleValue(), as every Number should provide the methods listed here.
Edit: As stated in the comments, you will (always) have to check for BigDecimal and friends. But they provide a .compareTo() method:
if(yourNumber instanceof BigDecimal && otherNumber instanceof BigDecimal) {
boolean greaterThanOtherNumber = ((BigDecimal)yourNumber).compareTo((BigDecimal)otherNumber) > 0;
}
You can simply use Number's doubleValue() method to compare them; however you may find the results are not accurate enough for your needs.
Let's assume that you have some method like:
public <T extends Number> T max (T a, T b) {
...
//return maximum of a and b
}
If you know that there are only integers, longs and doubles can be passed as parameters then you can change method signature to:
public <T extends Number> T max(double a, double b) {
return (T)Math.max (a, b);
}
This will work for byte, short, integer, long and double.
If you presume that BigInteger's or BigDecimal's or mix of floats and doubles can be passed then you cannot create one common method to compare all these types of parameters.
If your Number instances are never Atomic (ie AtomicInteger) then you can do something like:
private Integer compare(Number n1, Number n2) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Class<? extends Number> n1Class = n1.getClass();
if (n1Class.isInstance(n2)) {
Method compareTo = n1Class.getMethod("compareTo", n1Class);
return (Integer) compareTo.invoke(n1, n2);
}
return -23;
}
This is since all non-Atomic Numbers implement Comparable
EDIT:
This is costly due to reflection: I know
EDIT 2:
This of course does not take of a case in which you want to compare decimals to ints or some such...
EDIT 3:
This assumes that there are no custom-defined descendants of Number that do not implement Comparable (thanks #DJClayworth)
In my use case, I was looking for a general Comparator that works with the autoboxed primitives (64 bit max precision), not arbitrary precision types like BigInteger and BigDecimal. Here's a first shot at it..
public class PrimitiveComparator implements Comparator<Number> {
#Override
public int compare(Number a, Number b) {
if (a == b)
return 0;
double aD = a.doubleValue();
double bD = b.doubleValue();
int comp = Double.compare(aD, bD);
if (comp == 0 && inLongBounds(aD))
comp = Long.compare(a.longValue(), b.longValue());
return comp;
}
private boolean inLongBounds(double value) {
return
Double.compare(value, Long.MAX_VALUE) <= 0 &&
Double.compare(value, Long.MIN_VALUE) >= 0;
}
}
The objective is to be able to compare mixed types (e.g. Floats against Longs). This should also work with those AtomicXxx types (or any hand rolled Number subclass that uses no more than 64 bits).
In this ordering, btw, Double.NaN > Double.POSITVE_INFINITY > { everything else }.
I am thinking about something like this:
public static <T extends Comparable<T>> T minOf(T...ts){
SortedSet<T> set = new TreeSet<T>(Arrays.asList(ts));
return set.first();
}
public static <T extends Comparable<T>> T maxOf(T...ts){
SortedSet<T> set = new TreeSet<T>(Arrays.asList(ts));
return set.last();
}
But is not null safe, which is something I want too.
Do you know a better way to solve this problem?
EDIT:
After the comments I have also tried min():
public static <T extends Comparable<T>> T minOf(T...ts){
return Collections.min(Arrays.asList(ts), new Comparator<T>(){
public int compare(T o1, T o2) {
if(o1!=null && o2!=null){
return o1.compareTo(o2);
}else if(o1!=null){
return 1;
}else{
return -1;
}
}});
}
What do you think of that?
What's wrong with Collections.max?
And why do you care about null safety? Are you sure you want to allow nulls to be in your Collection?
If you really need to exclude "null" from the result, and you can't prevent it from being in your array, then maybe you should just iterate through the array with a simple loop and keep track of the "min" and "max" in separate variables. You can still use the "compare()" method on each object to compare it with your current "min" and "max" values. This way, you can add your own code for checking for nulls and ignoring them.
EDIT: here's some code to illustrate what I'm talking about. Unfortunately there is an edge case you need to consider - what if all of the arguments passed in are null? What does your method return?
public static <T extends Comparable<T>> T minOf(T...ts){
T min = null;
for (T t : ts) {
if (t != null && (min == null || t.compareTo(min) < 0)) {
min = t;
}
}
return min;
}
public static <T extends Comparable<T>> T maxOf(T...ts){
T max = null;
for (T t : ts) {
if (t != null && (max == null || t.compareTo(max) > 0)) {
max = t;
}
}
return max;
}
You should not implement Comparable to accept null, as it breaks the interface's contract.
From https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html :
Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.
You must instead create a new interface, e.g. ComparableNull instead.
See also:
What should int compareTo() return when the parameter string is null?
How to simplify a null-safe compareTo() implementation?