Issue
I have read several pages on generic methods and have some sort of grasp on them, but I still don't understand them. So say I have a method to multiply two numbers and return the product:
public double multiply(SomeNumberVariableType x, SomeNumberVariableType y){
return x * y;
}
How can I use bounded generics to have only a number type permitted as parameters?
Solution
Maybe this is your intention:
public static <N extends Number> double multiply(N x, N y){
return x.doubleValue() * y.doubleValue();
}
Although I must also say that the generic use of Number instead of concrete immutable value types like java primitive double
is probably not so healthy because in the example above the arguments could even be of different types, for example Integer and Double.
Attention:
I confirm, the arguments can be of different types as given signature above. So the answer of Bohemian is wrong. I have tested it just now (but knew it already before). The compiler only guarantees that both arguments are of type Number, nothing else.
In order to assert the same argument types the compiler needs self-referencing generics. This feature is not fulfilled by Number-class (that is <N extends Number<N>> is unfortunately not possible). That is why I consider the whole Number approach as not really healthy. Here a test code which everyone can execute:
Integer x = Integer.valueOf(10);
Double y = new Double(2.5);
System.out.println(multiply(x, y));
// Output: 25.0
Answered By - Meno Hochschild
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.