jdk 1.5 generics and return types

Discussion in 'Java' started by Ian, Jul 25, 2005.

  1. Ian

    Ian Guest

    Hi,

    I've got a question related to typing when using the new generics.

    In the following, is there any way to specify the type of collection if
    its known by the caller? Lets say the type of the objects to be return
    is "Action".

    static Collection getInstances(Collection<String> classNames,
    Object ... args)
    {
    Collection instances = new ArrayList();
    for (String className : classNames)
    {
    Object obj = getInstance(className, args);
    instances.add(obj);
    }
    return instances;
    }
     
    Ian, Jul 25, 2005
    #1
    1. Advertising

  2. Ian

    E.Otter Guest

    Sure.... You have to remember that Collection is an interface so you have
    to create an object of a class that implements the Collection interface in
    some way. For example, create an ArrayList<Action> and then return the
    reference to that.

    static Collection<Action> getInstances(Collection<String> classNames, Object
    .... args) {

    ArrayList<Action> returnVals = new ArrayList<Action>();

    ... code that stores stuff in "returnVals" ...

    return returnVals;
    }

    E.Otter
     
    E.Otter, Jul 26, 2005
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Robert Elliot
    Replies:
    10
    Views:
    1,169
    Robert Elliot
    Jun 6, 2004
  2. Webb  Roberts

    Generics? Covariant return types?

    Webb Roberts, Nov 10, 2005, in forum: Java
    Replies:
    3
    Views:
    415
    Thomas Hawtin
    Nov 10, 2005
  3. Steve Knight
    Replies:
    2
    Views:
    780
    Steve Knight
    Oct 10, 2003
  4. Ulf Meinhardt
    Replies:
    0
    Views:
    6,453
    Ulf Meinhardt
    Aug 10, 2006
  5. kelvSYC

    Generics in return types

    kelvSYC, Dec 13, 2007, in forum: Java
    Replies:
    2
    Views:
    275
    kelvSYC
    Dec 13, 2007
Loading...

Share This Page