• 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

Generic method problem

 
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Ranchers

What exactly does the following method body trying to declare??

public <T> List<T> meth(List<?> l)
{
return new arrayList<String>();
}

It gives compiler error, but I couldnt understand how this works.
Any help would be greatly appreciated.
 
Mohit Jain
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I would appreciate if somebody could provide an explanation for this.
 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I expect the method declaration to be

public List<T> meth(List<T> l)
{
return new ArrayList<T>();
}

If that is the case, it should be implemented something like this
public List <String> meth (List <String> l)
{
return new ArrayList <String>();
}

Read generics, you will get hold of this.
 
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Disclaimer: I'm still trying to get the generics concepts down so please cross reference my answer LOL



If you had to keep the last line returning new arrayList<String> then you're return type generic in the method's signature should reflect that:

and I think (not sure) you can say:

which would actually allow you the option to return a list of type Objects or Strings.

I don't see why you couldn't keep the paramter list as List<?> which will allow you to pass in any type of List, especially if you're not returning that exact same List. So if the caller passed a list of type parameter<Animal> you could still return a different List<String> that was created within the method body.

Am I right bartenders? This is an area that I'm trying to get down myself :roll:
reply
    Bookmark Topic Watch Topic
  • New Topic