开发者

Using an object to instantiate a collection

开发者 https://www.devze.com 2023-03-09 13:20 出处:网络
I would like to do the following (which doesn\'t work, it is just to explain the concept). Any idea how to do it?

I would like to do the following (which doesn't work, it is just to explain the concept). Any idea how to do it?

开发者_JS百科
Class type;
if (/* something */)
  type = String.class;
else
  type = Boolean.class;

return new ArrayList<type>();

ArrayList<type> doesn't work. I tried with type.getClass(), doesn't work either.


Wrap it into the method, pass the type as generic Class and let Java do the rest for you. No need for any conditional branching.

<T> List<T> newList(Class<T> type) {
    return new ArrayList<T>();
}

Then you can use it like this:

List<String> list = newList(String.class);

Bear in mind that T does not have to be specified at the generic class level. You can specify generic type for the method and therefore make it a generic method as in the example code.


You can't do that. Your check happens at runtime and generics are lost after compilation.

The only purpose of generics is to guarantee type-safety at compile-time. In your example you want to determine the type at runtime.

What you can do is to instantiate a differently-typed collection in each if.


you should use:

public ArrayList<?> getList() {
    if (/* something */) {
        return new ArrayList<String>();
    } else {
        return new ArrayList<Boolean>();
    }
}


Type information is deleted by the Java compiler but can be accessed through additional packages such as this one


type isn't a class , You can have multiple return in this case You can have this

public <T> List<T> foo(T type) {
    return new ArrayList<T>();
}


The if clause is presumably something that is decided at run-time. The parameterised types in java are cleared at compile time. Just returning new ArrayList() will have the same effect.

0

精彩评论

暂无评论...
验证码 换一张
取 消