Question

In this topic i faced with implict types.

Question 1. What's strong defenition of implicit type in Java or it's non-formal concept? Can i define implicit type manually? Is it true that all of implicit type is the same? What's the implicit type for compiler?

The following code example:

List<? extends Number> nums= new ArrayList<Integer>();
nums.add(3);//error

I know that we can assign to nums reference to ArrayList<Double>.

Question 2. In this context ? extends Number is implicit type, defined by CAP#1. Is it true that compiler does know that only null is instance of this implicit type?

Was it helpful?

Solution

The proper term is capture of wildcard. Compiler internally converts the wildcard instantiation of a generic type to the capture of the wildcard. The capture represents the particular unknown type of the type argument. This particular unknown type is, of course, a member of the type family that the wildcard denotes.

Note that, since there can be many different types that can be represented by wildcard instantiation, we say that wildcards represent a family of different instantiation of a parameterized types.

Can i define implicit type manually?

Anonymous type variable? No. That is created by compiler internally. You can say that, you are instructing the compiler to create an anonymous type argument which will replace the wildcards used.

Is it true that all of implicit type is the same?

No. If you use say List<? extends Number> twice as different types, they both will generate different anonymous types, viz, CAP#1 extends Number and CAP#2 extends Number.

What's the implicit type for compiler?

I don't understand these questions.

Is it true that compiler does know that only null is instance of this implicit type?

The reason why adding null works is due to the fact that, null is a valid value for any kind of reference. So, whatever the actual type argument the wildcard represent, would happily accept the value null.

OTHER TIPS

You cannot put anything into a type declared with an extends wildcard except for the value null, which belongs to every reference type

List<Integer> ints = Arrays.asList(1,2,3);
List<? extends Number> nums = ints;
nums.add(null); // ok
assert nums.toString().equals("[1,2,3,null]");

In general, if a structure contains elements with a type of the form ? extends E, we can get elements out of the structure, but we cannot put elements into the structure (except null). To put elements into the structure we need super wildcard:

    List<Number> nums = new ArrayList<Number>();
    nums.add(2);
    nums.add(3.14);

    List<? super Integer> ints = nums;

    ints.add(3); 
    ints.add(null);

Result: [2, 3.14, null]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top