tanisha Murthy

Greenhorn
+ Follow
since Jul 15, 2009
Merit badge: grant badges
For More
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by tanisha Murthy

Hi Adrian

Iam planning to give SCJP 6. But I do not have any prior java experience or java knowledge. Iam looking for a good book to study. Can you please tell me one.

14 years ago

Henry Wong wrote:

tanisha Murthy wrote:Then in that case whatever we specify in place of <String>, like <Integer> or <Float> would be resulting in compiler error, because compiler will not know the unknown type is correct or not.




Which is why, in the case of <? extends Object>, you can't add() anything -- except for null. The compiler can't verify the type.

It is a bit different when it is a "super" bounded wildcard, as the compile can check it, even if it is unknown.

Henry



In generics type checking happens at compile time....then in that case why cant the compiler verify the type. For "List<? extends Object> a=new Vector<String>();", you are telling compiler will not know that String is the unknown type which extends from object. Then why is the type checking hapening at compile time.
When we are adding null, there should be type checking??? One Answer leading to n number of questions
Then in that case whatever we specify in place of <String>, like <Integer> or <Float> would be resulting in compiler error, because compiler will not know the unknown type is correct or not.
Here is the question:

what is the result of compiling and running the given code?
List<? extends Object> a=new Vector<String>();
a.add("USA");
a.add("Russia");
a.add("UK");
for (String s: a)
System.out.println(s);

The given options are
1.compiler error :Incorrect syntax used for declaration of the generic type a
2.compiler error : Vector object cannot be assigned to a List type variable
3.Compiles correctly and prints"USAUKRUSSIA"
4.Compiles correctly and prints "USA" "UK" and "RUSSIA" in an order which cannot be predicted
5.none of these


Thanks for your response.
List<? extends Object> a=new Vector<String>();

Here String class extends Object class , so "a" should be able to add"USA" ,"UK , "RUSSIA"

Henry Wong wrote:Is there a question somewhere?

Henry




I found this question on whizlabs SCJP mock test.
I was unable to figure out the error in the code.
List<? extends Object> a=new Vector<String>();
a.add("USA");
a.add("Russia");
a.add("UK");
for (String s: a)
System.out.println(s);


In the above code fragment, there is something wrong with a.add(). I could not figure out, the problem, can anyone help!!!