3

I have a method signature like

public <T extends SomeClass> T[] findAll(Class<T> oClass, String condition)

But I'm not sure how I can create that T[] type from Class<T>. I've tried using a Collection<T> but I cannot cast (T[]) collection.toArray() and Array.newInstance(Class<?>, int) asks for an array class (i.e. T[]) already, which is of no use and redundant.

Also, obvisously, new T[n] does not work.

I would presume it's something easy, but I'm numb for the solution right now :)

Thanks.

1 Answer 1

5

newInstance does not ask for an array class, it asks for the component type. It will work fine, albeit with the usual problems with unchecked casts and generic arrays.

T[]  myArr = (T[]) Array.newInstance(oClass, length);

But why mix arrays and Generics at all? It'll just lead to headaches. Use something from the Collections API, like List.

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

4 Comments

Yes, perhaps a Collection like a List should be fine, but since I don't want the returned value to be modifiable, I prefer to have an array instead of Collections.unmodifiableList()
@Yanick: But you can always modify an array! Collections.unmodifiableList() does a much better job of keeping your collection unmodifiable.
yes, of course, I was referring more about the add and remove methods; you can't add or remove items in an array. Replacing a value if of no concern, but point taken.
@Yanick: If you have an array (of any reference type), you can use Arrays.asList(array) to convert it into a fixed-lenght list. So you could use an empty Object[], wrap it into a list, cast the list to the right generic type, and then fill it (or first fill, then make list). This needs a SuppressWarning, but if the array stays in your method, it should be safe.

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.