Java generics gotchas: same erasure error 

Joined:
04/09/2007
Posts:
775

June 27, 2011 13:12:36    Last update: June 27, 2011 13:12:36
Parameterized types are considered different at compile time but not at runtime. This program fails compilation because List<Foo> is not the same as List<Bar>:
import java.util.ArrayList;
import java.util.List;

public class SameErasure {
    public static void main(String[] args) {
	SameErasure se = new SameErasure();
	List<Bar> l = new ArrayList<Bar>();
	se.doWork(l);
    }

    public void doWork(List<Foo> l) {
    }
}

class Foo {
}

class Bar {
}

Error:
$ javac SameErasure.java
SameErasure.java:8: doWork(java.util.List<Foo>) in SameErasure cannot be applied to (java.util.List<Bar>)
	se.doWork(l);
	  ^
1 error


This also fails because List<Foo> and List<Bar> are considered the same:
import java.util.ArrayList;
import java.util.List;

public class SameErasure {
    public static void main(String[] args) {
	SameErasure se = new SameErasure();
	List<Bar> l = new ArrayList<Bar>();
	se.doWork(l);
    }

    public void doWork(List<Foo> l) {
    }

    public void doWork(List<Bar> l) {
    }
}

class Foo {
}

class Bar {
}

Error:
$ javac SameErasure.java
SameErasure.java:11: name clash: doWork(java.util.List<Foo>) and doWork(java.util.List<Bar>) have the same erasure
    public void doWork(List<Foo> l) {
                ^
SameErasure.java:14: name clash: doWork(java.util.List<Bar>) and doWork(java.util.List<Foo>) have the same erasure
    public void doWork(List<Bar> l) {
                ^
2 errors
Share |
| Comment  | Tags