Pierre Guilbert
Pierre Guilbert

Reputation: 5177

Generic type as parameter in Java Method

Do you think it is possible to create something similar to this?

private ArrayList increaseSizeArray(ArrayList array_test, GenericClass) {
    array_test.add(new GenericObject()); // instance of GenericClass
    return array_test;
}

Upvotes: 62

Views: 154223

Answers (4)

Brad Parks
Brad Parks

Reputation: 72283

You can do so, and this page in Oracle's docs show you how

// Example of a void method
<T> void doSomething(T someT) {
  // Do something with variable
  System.out.println(someT.toString());
}

// Example of a method that returns the same generic type passed in.
<T> T getSomeT(T someT) {
  return someT;
}

Upvotes: 3

Aarjav
Aarjav

Reputation: 1374

Old question but I would imagine this is the preferred way of doing it in java8+

public <T> ArrayList<T> dynamicAdd(ArrayList<T> list, Supplier<T> supplier) {
  list.add(supplier.get());
  return list;
}

and it could be used like this:

AtomicInteger counter = ...;
ArrayList<Integer> list = ...;

dynamicAdd(list, counter::incrementAndGet);

this will add a number to the list, getting the value from AtomicInteger's incrementAndGet method

Also possible to use constructors as method references like this: MyType::new

Upvotes: 13

user5536522
user5536522

Reputation:

simple solution!

private <GenericType> ArrayList increaseSizeArray(ArrayList array_test, GenericType genericObject)
{
    array_test.add(new genericObject());
    return ArrayList;
}

Upvotes: 3

C. K. Young
C. K. Young

Reputation: 223183

Yes, you can.

private static <T> List<T> pushBack(List<T> list, Class<T> typeKey) throws Exception {
    list.add(typeKey.getConstructor().newInstance());
    return list;
}

Usage example:

List<String> strings = new ArrayList<String>();
pushBack(strings, String.class);

Upvotes: 115

Related Questions