Java return datatype when class is stored in an array

Imix :

This is my sample class

public class Value<E> {
    public final E value;

    public Value(E value) {
        this.value = value;
    }
}

And this returns a String and no Object, so I don't need to cast it.

String a = new Value<String>("test").value;

However, if I want to do this, then I need to cast it.

ArrayList<Value<?>> a = new ArrayList<>();
a.add(new Value<String>("test"));

String b = a.get(0).value; // Runtime error

If I add the value to the ArrayList it returns an Object, but I want it to return what I defined the Element to be. How can I solve this?

Kayaman :

You can't. You defined that you don't know (or care) what types are contained inside with Value<?>, so you can only treat them as Object as that's the one thing they're guaranteed to be (they can also be subclasses, but they'll still always be Objects too).

If you think and hope you can store Strings and Integers in the same List, that's not possible except by treating them as Objects. Besides, you shouldn't be storing different types (except through inheritance hierarchy) in the same collection anyway.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=25258&siteId=1