Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"both methods have same erasure" error using bounded type parameters

I'm using generics in Java for the first time, and I'm facing an issue I don't manage to overcome: why this compiles:

public interface Aa{}
public interface Bb{}
public interface Cc{}


public static <GenericAB extends Aa & Bb>
void method(GenericAB myABobject1, GenericAB myABobject2){}

public static <GenericAB extends Aa & Bb, GenericCA extends Cc & Aa>
void method(GenericAB myAbobject, GenericCA myCAobject){}

But this does not:

public interface Aa{}
public interface Bb{}
public interface Cc{}


public static <GenericAB extends Aa & Bb>
void method(GenericAB myABobject1, GenericAB myABobject2){}

public static <GenericAB extends Aa & Bb, GenericAC extends Aa & Cc>
void method(GenericAB myAbobject, GenericAC myACobject){}

And I get this error: both methods have same erasure.

I'm sorry if this is a stupid question, but I don't get why the order of interfaces in a bounded type parameter declaration seems to have importance. In reality I don't think it is the order which causes the error, but I don't get what does.

I'm reading this documentation by Oracle, it says which I must put the class as first parameter but Aa, Bb and Cc are all interfaces. Sorry for my english too.

like image 890
Lapo Avatar asked May 29 '18 18:05

Lapo


People also ask

What are the two 2 types of Erasure?

- Erasure is a type of alteration in document. It can be classified as chemical erasure and physical erasure.

What is type erasure and explain the functionality of type erasure with example?

Type erasure is a process in which compiler replaces a generic parameter with actual class or bridge method. In type erasure, compiler ensures that no extra classes are created and there is no runtime overhead.

What is erasure Why is erasure important in Java generics implementation?

Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.

How does type erasure work?

What Is Type Erasure? Type erasure can be explained as the process of enforcing type constraints only at compile time and discarding the element type information at runtime. Therefore the compiler ensures type safety of our code and prevents runtime errors.


1 Answers

It is the order that matters (§4.6):

The erasure of a type variable (§4.4) is the erasure of its leftmost bound.

GenericBC erases to either Aa or Cc, depending on which appears first (i.e. leftmost) in the bound.

Also see type erasure tutorial and type erasure, when and what happens Q&A for explanations of type erasure in general.

like image 93
Radiodef Avatar answered Oct 02 '22 18:10

Radiodef