1

I have some Class objects in a List that I would like to convert into an array. Below is my code:

private static Class<?>[] getClasses(final Object[] params) {
    List<Class<?>> classList = new ArrayList<>();

    for (final Object param : params) {
        classList.add(param.getClass());
    }

    return (Class<?>[]) classList.toArray();
}

I understand toArray() returns an Object[]. Is there a way to avoid the cast?

1
  • Why not just create an array of Class instead of making List of Class? Commented Jul 21, 2017 at 5:22

2 Answers 2

2

You can use the toArray method with the array as parameter:

return classList.toArray(new Class<?>[classList.size()]);
Sign up to request clarification or add additional context in comments.

Comments

2

You can just create a new array and put each element in, one by one:

Class<?>[] classes = new Class<?>[classList.size()];
for (int i = 0 ; i < classList.size() ; i++) {
    classes[i] = classList.get(i);
}

Or, rewrite the whole method without using the list:

    private static Class<?>[] getClasses(final Object[] params) {
        Class<?>[] classList = new Class<?>[params.length];

        for (int i = 0 ; i < classList.length ; i++) {
            classList[i] = params[i].getClass();
        }

        return classList;
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.