56

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;
}
Pierre Guilbert
  • 5,057
  • 3
  • 19
  • 19

4 Answers4

106

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);
C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • 2
    How do you call that method? I don't know what Class typekey should be. I can't find anything about it. If you have any reading advice, it will be welcome. Thank you for your response! – Pierre Guilbert Jul 21 '11 at 08:53
  • 1
    @Pierre: Just added a usage example. Basically, if you take a class name (`String` in this case) and add `.class` after it, you have a type key (class object) for that class. `String.class` has type `Class`. – C. K. Young Jul 21 '11 at 14:37
  • I just used it like this: static List pushBack(List list, Class typeKey, int size) and it worked. Thank you, you helped me a lot. Avoiding copy/paste code is always a joy. – Pierre Guilbert Jul 25 '11 at 13:38
  • 1
    Why is used just before return type ? I am also doing the same thing but i want to know the actual usage of . Thanks in advance. – Deepak Gangore Sep 14 '16 at 05:52
  • https://docs.oracle.com/javase/tutorial/extra/generics/methods.html introduces the construct of `static void method(...)` – Douglas Held Sep 01 '17 at 09:58
  • Correction... https://docs.oracle.com/javase/tutorial/java/generics/methods.html actually introduces the syntax (the above link I provided does not). – Douglas Held Sep 01 '17 at 10:13
12

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

Aarjav
  • 1,334
  • 11
  • 22
3

simple solution!

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

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;
}
Brad Parks
  • 66,836
  • 64
  • 257
  • 336