user3657850
user3657850

Reputation: 552

Java: Same name but different generic type

I wanna use an ArrayList for my Code but it should contain different types of Objects. So it should be sth like this:

 switch (foo) {
        case "foo1":
            list=new ArrayList<foo1>();
            break;
        case "foo2":
            list = new ArrayList<foo2>();
            break;

I know the posted Code does not work but is it possible to make sth similar.

And before you ask there should be multiple actions performed on this List but i dont wont to write everything again just with a different name for the List.

public class foo1 {}

public class foo2 {}

    import java.util.ArrayList;
public class work{
    public static void main(String[] args){
    ArrayList<?> list;
     switch (args[0]) {
            case "foo1":
                list=new ArrayList<foo1>();
                break;
            case "foo2":
                 list= new ArrayList<foo2>();
                break;
            default:
                System.out.println("Some Error Text");
                return;

        }
     list.add(new foo1());
    }
}

Upvotes: 2

Views: 240

Answers (1)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79875

What you're asking for is entirely pointless because of type erasure. Type parameters cease to exist at run time, so the thing you get from new ArrayList<Foo1> is exactly the same as the thing you get from new ArrayList<Foo2>.

In other words, type parameters are information for the compiler only. And with the code that you're working with, the compiler really only cares about the declared type of list, not the type that you supply when you instantiate it.

Of course, your code will compile if you've declared

ArrayList<?> list;

or

List<?> list;

or you can narrow it down if Foo1 and Foo2 have a common supertype (other than Object) - say they are both subtypes of Foo, you can write

List<? extends Foo> list;

but why would you bother?

Upvotes: 5

Related Questions