[HD-OCP17/21-Fundamentals Pg 0, Sec. 16.1.3 - inferencing-the-type-from-lt-gt]

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
dtruebin
Posts: 8
Joined: Wed Jun 18, 2025 4:39 am
Contact:

[HD-OCP17/21-Fundamentals Pg 0, Sec. 16.1.3 - inferencing-the-type-from-lt-gt]

Post by dtruebin »

For example, you can safely assume that the type inferred by the compiler in all of the following statements, including the fourth, is Number, even if that assumption turns out to be incorrect (as it will for the fourth line).
<...>

Code: Select all

ArrayList<?> list4 = new ArrayList<>();
This doesn't look right. Why would we, in this 4th case, be able to safely assume the inferred type to be Number?

admin
Site Admin
Posts: 10408
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: [HD-OCP17/21-Fundamentals Pg 0, Sec. 16.1.3 - inferencing-the-type-from-lt-gt]

Post by admin »

No, it is fine. The note is about the type of the reference inferred by the compiler for the object created on the right hand side of = (because that is where you are using <> ).
The sentence before the one that you have quoted is this:
You will never need to know what the inferred type is because your view into the object is determined solely by the type of the reference variable
that you are using, which you already know.
So, it doesn't really matter what you assume because you will write your code as per the type of the variable (i.e. the type specified on the left hand side).

In the case of ArrayList<?> al = new ArrayList<>(); you can safely assume that the type inferred by the compiler when it sees <> is Number (or even a String or whatever) and it wouldn't matter because your view is determined by the type of the variable al (not by the type of the object on the right hand side). You can only get an Object from al because its type is ArrayList<?>.

The complete sentence is,
For example, you can safely assume that the type inferred by the compiler in all of the following statements, including the fourth, is Number, even
if that assumption turns out to be incorrect (as it will for the fourth line)
.

Post Reply

Who is online

Users browsing this forum: No registered users and 30 guests