Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with the following generics code? [duplicate]

Tags:

java

generics

Following code is throwing compile time exception

Type mismatch: cannot convert from Integer to K

What I understand is K should handle any value that extends Number.

public <K extends Number> K getValue(){
    Integer a = new Integer(1);
    return a;//Type mismatch: cannot convert from Integer to K
}

(Note: This is just a test code to put my question without giving irrelevant details of my actual scenario.)

like image 312
ManishKr Avatar asked Nov 25 '16 17:11

ManishKr


People also ask

What is wrong with code duplication?

1. Duplicate code makes your program lengthy and bulky : Many programmers feel that if the software is working properly there is no reason to fix code duplications. You forget that you are just un-necessarily making your software bulky.

Why do we avoid code duplication?

Having to change the same code multiple times harms your cycle time. If you have to apply a change in multiple places, then implementing that change will take longer. If the duplication is pervasive enough, it'll lead to a decreased delivery speed.

Is duplicate code a code smell?

👬 1 - Code Duplication This code smell occurs when there are identical or very similar pieces of code in more than one location. There's also more subtle duplication when specific parts of code look different but perform the same job.

What is wrong with Java generics?

The main problem is that Java doesn't actually have generics at runtime. It's a compile time feature. When you create a generic class in Java they use a method called "Type Erasure" to actually remove all of the generic types from the class and essentially replace them with Object.


1 Answers

The problem here is the fact that K is a type that extends Number but it is an unknown sub class of Number that is why the compiler raises this error because Integer is only one specific sub class of Number so it cannot match with any potential target types.

Let's say that you want to cast it explicitly to make it compile with

public <K extends Number> K getValue(){
    Integer a = new Integer(1);
    return (K) a;
}

Then if you call it expecting any sub class of Number except Integer you will get a ClassCastException, that is exactly what the compiler wants to avoid:

Double d = getValue(); <-- throws ClassCastException

As workaround you could define your method using Number as returned type as next:

public Number getValue() {
    return new Integer(1);
}
like image 160
Nicolas Filotto Avatar answered Oct 18 '22 14:10

Nicolas Filotto