0

Im looking to see if it is at all possible to create an array of type, where the type is passed in as a parameters for example:

public void doSomething(Class<?> itemClass){

    ArrayList<itemClass> newItems = new ArrayList<itemClass>();
}

But that obviously doesn't compile. Is it possible to do something like this?

0

1 Answer 1

1

Try this:

private <T> void makeTypedArray(Class T) {
  ArrayList<T> typedArray = new ArrayList();
}

The above is the only way I know of to pass a usable type to a method in Java.

Sign up to request clarification or add additional context in comments.

3 Comments

So the actual object parameter does nothing here? or?
The way I have done it in the past, the passed object tells the method what type to use for T. If you don't want to pass an instance of the class you can probably just pass Class T. Edited my answer.
1. Raw types should be avoided. There is no reason to use new ArrayList() instead of new ArrayList<T>() or new ArrayList<>(). And Class is also a raw type. 2. The parameter is not used, and should thus be removed. 3. The parameter is confusingly named to be the same as the type T, which makes no sense.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.