• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Genericss

 
Ranch Hand
Posts: 664
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 210
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
reply
    Bookmark Topic Watch Topic
  • New Topic