This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
I know that ? wildcard stands for any type. I also know that with List<Object> I can add to the List only Objects..not a String, not a Integer and so on. But with List<?>, you mean to say I cannot add anything? Am I right?
Originally posted by Jothi Shankar Kumar Sankararaj: I also know that with List<Object> I can add to the List only Objects..not a String, not a Integer and so on. Am I right?
No. You can add Integers, Strings, Foos or anything else to a List<Object>. You might have to cast them when they come out, which rather defeats the purpose of using generics in the first place, however.
Ok, got the difference. When we cannot add anything to a list when we say List<?>, then why does the compiler allow to create one such thing?
Joined: Oct 13, 2005
Surely you declare a List as unknown type (List<?>) and you initialise it to a particular type?
You will have to go through the standard references, vizthe Java Tutorials and do a Google search for Angelika Langer who has a website with FAQs about Java generics. [ September 15, 2008: Message edited by: Campbell Ritchie ]
author & internet detective
Originally posted by Jothi Shankar Kumar Sankararaj: When we cannot add anything to a list when we say List<?>, then why does the compiler allow to create one such thing?
Creating one in the same line you are instantiating the list isn't very useful. List<?> comes in handy when it is used as a method parameter. method(List<?> list) allows me to take any type of list in provided a promise not to edit it.
Originally posted by Jothi Shankar Kumar Sankararaj: I really did not get your explanation. Can you be a bit clear?
You have a List<Date>. You then cast it to an Object, which is just perfectly legal. After all, every non-primitive IS-A Object in Java. However, then you are casting it to List<String>. The compiler gives you a warning. It doesn't give you an error because the object could be a List<String>. It can't tell though.
Now why this gives a warning and casting without generics (e.g. (Date)object) doesn't is because of type erasure. In the byte code created by the compiler, the <Date> part is removed. It effectively is just a List. Now during runtime you can check if an object is a Date or List (using instanceof), but you can't check if an object is a List<Date> - because the <Date> part is no longer there.