Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Genericss

 
Nabila Mohammad
Ranch Hand
Posts: 664
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
These are three codes take from John Meyer's Mock.
All the code are similiar and all of them give a Compile time error.




This code says it does not compile at 2. List is required ( I agree!)


In this code the answer mentioned is A List<?> is expected so it can be any Object.
Does this mean - it again does not compile because an ArrayList is returned and not a List.
OR does it mean that if it returned a List of anytype it would have compiled.
( I am still confused with the T type ...)




In this code it simply mentions that it does not compile because of line 2.
IS because it returns and ArrayList and not List.
Or is it because of it returns an ArrayList<String> type.


Still Struggling with Generics
 
ramesh maredu
Ranch Hand
Posts: 210
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public <T> List<T> meth(List<?> type)
{
System.out.println(type); // 1
return new ArrayList<String>(); // 2
}

Let us see what is T first here,the parameter T will be determined according to the method call. for example see below code.



above code compiles successfully.

and examine the code posted by you.You are returning new ArrayList<String>();
the returned value is always same for what ever the method call.
but your method's return type is call specific that is the reason it won't compile

below code compiles fine.

public <T> List<?> meth(List<T> type)
{
System.out.println(type); // 1
return new ArrayList<String>(); // 2
}
[ September 14, 2008: Message edited by: ramesh maredu ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic