Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java and generics. Isn't 0 a Number?

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?

like image 405
Ionuț G. Stan Avatar asked Jul 25 '11 22:07

Ionuț G. Stan


People also ask

How do you declare generics in Java?

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.

Why generics dont work with primitives?

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.

What is the difference between T and E in Java generics?

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 ).


1 Answers

While an Integer is a Number, an Integer might not be compatible to N which can be any subclass of Number.

like image 73
Christopher Oezbek Avatar answered Oct 27 '22 13:10

Christopher Oezbek