While I understand why both of the correct answers are correct, I'm struggling to figure out why
Code: Select all
List<?> list = new ArrayList<?>(Arrays.asList(names));
Can someone enlighten me?
Thanks
Nick
Moderator: admin
Code: Select all
List<?> list = new ArrayList<?>(Arrays.asList(names));
So then this must include inferring with an argument of unknown type (ie: <?> )You can replace the type arguments required to invoke the constructor of a generic class
with an empty set of type parameters (<>)
as long as the compiler can infer the type arguments from the context.
Code: Select all
List<?> myList = new ArrayList<>();
But then how is that any different to option 3? Option 1 and 3 seem to evaluate to the same, if <> is treated as <?>admin wrote:Yes, compiler infers the type of ArrayList as ? i.e. the unknown type from the declaration List<?>.
Sorry, I still don't understand. <?> IS on the other side for option 1. In option 1 <> on right side becomes <?> so option 1 and 3 become the same? But option 1 is deemed a correct answer and option 3 is deemed wrongadmin wrote:<> is NOT treated as <?>. <> is just a syntactical shortcut to avoid writing the name of the type given on the other side of =. If the other side has <?>, <> is treated as <?>. If the other Side has <X>, <> is treated as <X>
Therefore, in this case, <> will not resolve to <?> (because that will error out as explained in point 1). It will be resolved by using the type of the argument Arrays.asList(names).Note: It is important to note that the inference algorithm uses only invocation arguments, target types, and possibly an obvious expected return type to infer types. The inference algorithm does not use results from later in the program.
Users browsing this forum: No registered users and 222 guests