Java – What is the difference between wildcard and primitive type conversion?

What is the difference between wildcard and primitive type conversion?… here is a solution to the problem.

What is the difference between wildcard and primitive type conversion?

What is the difference between the following?

List <?> list = (List<?>) var;
List <String> list = (List) var;

Solution

Essentially, the difference is in one that makes your code type safe and one that makes it type unsafe.

If you convert to a primitive type, such as (List)var, you are essentially discarding the security provided by generics. var may be List<Integer>, and now that you’ve converted it, you can assign it to List<String> with no compiler prompts. You can even get a string from it (it should be List<Integer> and the compiler won’t prompt (but this throws an exception at runtime). So converting to a primitive type is like saying to the compiler:

I don’t know exactly what type of list this will be right now, but I will do at runtime. I can hold all this type information of all these variables in my head all at once, so you don’t need to worry about it! I’ll handle types on my own.

… If the compiler can already do it for you, then this is not a wise move. Humans tend to make mistakes.

Converting to a (bounded) wildcard is like saying to the compiler:

I don’t know exactly what type of list this will be right now, but I will do at runtime. I can’t hold all this type information of all these variables in my head all at once, so you have to give me an error whenever what I am doing might not succeed all the time, ok?

In this case, the compiler knows that you don’t know the generic arguments, so it doesn’t allow you to do certain things, such as adding String to List<?> because of ? You can still get Object from List<?> though, because whatever That is, it must be a subclass of Object

Related Problems and Solutions