62

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;
}

4 Answers 4

116

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);
Sign up to request clarification or add additional context in comments.

6 Comments

How do you call that method? I don't know what Class<T> 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: 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<String>.
I just used it like this: static <T> List<T> pushBack(List<T> list, Class typeKey, int size) and it worked. Thank you, you helped me a lot. Avoiding copy/paste code is always a joy.
Why <T> is used just before return type ? I am also doing the same thing but i want to know the actual usage of <T>. Thanks in advance.
docs.oracle.com/javase/tutorial/extra/generics/methods.html introduces the construct of static <T> void method(...)
|
13

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

Comments

3

simple solution!

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

Comments

3

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.