About Question enthuware.ocpjp.v7.2.1299 :

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

Moderator: admin

Post Reply
Crashtest
Posts: 18
Joined: Fri May 31, 2013 1:18 pm
Contact:

About Question enthuware.ocpjp.v7.2.1299 :

Post by Crashtest »

I find generics very hard so I would like to make sure I understand this correctly.
Second answer:
List<?>
(...) Thus, this will not allow you to add anything to it because the compiler doesn't know the exact class of objects contained by the list so it cannot check (...)
Is this relevant to this particular case? I think in this example we are only reading from the list, not adding anything.

Would I then be right to interpret this explanation in this way?

Since we are assigning an element from the List to Number variable (Number n = list.get(0);) we need to be sure it can only be a Number. With List<?> we could get anything and if it was e.g. an Object, we would not be able to assign it to Number.

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

Re: About Question enthuware.ocpjp.v7.2.1299 :

Post by admin »

Yes, it is not particularly relevant but the next sentence in the explanation that you quoted reads, "Further, this will only allow you to do this: Object o = list.get(index); because all the compiler knows is that this list contains objects."

The explanation in totality is trying to show you the complete picture about what List<?> means.

HTH,
Paul.

sir_Anduin@yahoo.de
Posts: 62
Joined: Fri Aug 07, 2015 2:16 pm
Contact:

Re: About Question enthuware.ocpjp.v7.2.1299 :

Post by sir_Anduin@yahoo.de »

if
List<?> is the same as List <? extends Object>

is List<Obejct> also the same?

if not, what is the difference?

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

Re: About Question enthuware.ocpjp.v7.2.1299 :

Post by admin »

There is a world of difference. List<?> means you don't really know what kind of objects are stored in the List, while List<Object> means that the list is supposed to store any kind of object.

This becomes important when you try to put stuff in them. Since you don't know what does List<?> supposed to contain, you can't add anything to it. What if the list is of Cats and you try to put Dogs? You can, of course, take out Object from it because everything is at least an Object.
OTOH, You can add anything to List<Object> because it is a List of Object objects!

I strongly suggest you to go through this: viewtopic.php?f=2&t=473

-Paul.

Post Reply

Who is online

Users browsing this forum: No registered users and 5 guests