First of all, I would limit acceptable types in your class and introduce method that compares the field with Number
or with other GenericNumber
and define your generic class like
public class GenericNumber<T extends Number> {
private T number;
public T getNumber() {
return number;
}
public void setNumber(T number) {
this.number = number;
}
public void setNumber(T number) {
this.number = number;
}
//constructors
public int compareTo(Number n) throws Exception {
if((number == null) || (n == null))
throw new Exception("Can't compare null values");
else if(number.doubleValue() > n.doubleValue)
return 1;
else if(number.doubleValue() == n.doubleValue)
return 0;
else
return 1;
}
public int compareTo(GenericNumber n) throws Exception {
if(n == null)
throw new Exception("Can't compare null values");
return compateTo(n.getNumber());
}
}
With this approach testing for equality of instances will transform into the following condition, with your objects: (r.compareTo(g) == 0)
.
If you don't want to use the java-flavoured comparing class method of this type you can, of course, typecast the fields and compare with =
operator.
For the behaviour you expect it is not right to make such an assignment because GenericNumber<Integer>
is not a subtype of GenericNumber<Number>
, as our intuition implies, though Integer is subtype of Number. To understand that suppose that in your case you would like to call a set method on an instance of GenericNumber<Number>
:
GenericNumber<Integer> i = new GenericNumber<Integer>();
Integer ii = 3;
i.setNumber(ii);
GenericNumber<Number> n = i;//suppose it will be consumed by compiler
//in this case it will be tempting to forget about i and use n instead, like in the following lines
Folat f = 2.5f;
n.setNumber(f);
//would be valid because method signature will be
//public void Number setNumber(Number number)
//but what actually happens is that you will try to call method of class
//GenericNumber<Integer> with signature public void Integer setNumber(Integer number)
As you see, the last line will cause an error, so you need to use generics with caution.
By the way, tutorial section on generics of then-Sun, now-Oracle site is worth visiting, namely:
http://docs.oracle.com/javase/tutorial/java/generics/index.html and/or
http://docs.oracle.com/javase/tutorial/extra/generics/index.html.