What is that I'm missing about this snippet of code?
public class Zero<N extends Number> {
public N zero() {
return new Integer(0);
}
}
It says:
Type mismatch: cannot convert from Integer to N
Thanks!
Update I've changed the snippet to use an integer. Same thing happens. And it happens even when creating an anonymous subclass of Number
. Could it be Eclipse that is faulty about this?
To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class. As you can see, all occurrences of Object are replaced by T.
As per Java Documentation, generic type variables can only be instantiated with reference types, not primitive types. This is supposed to come in Java 10 under Project Valhalla. Java's current erased implementation which produces one class for all reference instantiations and no support for primitive instantiations.
6 Answers. Show activity on this post. Well there's no difference between the first two - they're just using different names for the type parameter ( E or T ).
While an Integer is a Number, an Integer might not be compatible to N which can be any subclass of Number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With