CodeBlue
CodeBlue

Reputation: 15389

Creating an Arraylist of the specified parameter's type or its subtype

I intend to create a function with the following signature -

public static List<? extends Model> getList(Model T, int numberOfItems, StringReader reader)

Now, inside this function, I want to create an ArrayList that will contain the same type of objects as T or any of its subclasses, i.e T could be a Model object or any of its subtypes.

So far, I tried -

   List < ? extends T> list = new ArrayList();

But it didn't work. How to get this to work?

Upvotes: 1

Views: 353

Answers (5)

android developer
android developer

Reputation: 116332

public static <T extends Model> List<T> getList(final Model t, final int numberOfItems, final StringReader reader)
{
    final List<T> aaa=new ArrayList<T>();
    return null;
}

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200148

You'll have to pass in the Class instance as a type marker. Something like this:

public static <T extends Model> List<T> getList(
    Class<T> c, int numberOfItems, StringReader reader)
{
  final List<T> l = new ArrayList<T>();
  try { for (int i = 0; i < numberOfItems; i++) l.add(c.newInstance());
  } catch (Exception e) { throw new RuntimeException(e); }
  return l;
}

I don't know how you want to use the StringReader so I left it aside. Call the method with a class literal. Say you've got a SubModel extends Model, then

final List<SubModel> l = getList(SubModel.class, 10, reader);

Upvotes: 2

Guillaume Polet
Guillaume Polet

Reputation: 47608

This returns a list of type T (and T is either of type Model or one of its subclasses).

public static <T extends Model> List<T> getList(T object, int numberOfItems, StringReader reader) {
    return Arrays.asList(object);
}

Upvotes: 0

Michael Borgwardt
Michael Borgwardt

Reputation: 346260

What you probably want is this:

public static <T extends Model> List<T> getList(T model, int numberOfItems, StringReader reader)

This specifies that the method has a type parameter T which extends Model, so the method can be used with any such type and for that call will return a List of the type that was passed as first parameter. Inside the method:

List <T> list = new ArrayList();

Upvotes: 2

Louis Wasserman
Louis Wasserman

Reputation: 198033

I think what you're asking for is

public static <M extends Model> List<M> getList(M t, int numberOfItems, ...)

Upvotes: 0

Related Questions