Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

Code does

Java
Object[] raw = list.toArray();
String[] names = (String[]) raw;

and fails with ClassCastException at runtime although every element is a String. Explain why, and also why a generic method

XML
<T> T[] toArray(List<T> l) {
return (T[]) l.toArray();
}

is dangerous.

list.toArray() with no arguments always creates an Object[], and arrays keep their real type at run time, so an Object[] can never be cast to String[], even if every element is a String. The generic method <T> T[] toArray(List<T> l) { return (T[]) l.toArray(); } is dangerous because the cast is unchecked: it does nothing at run time, so the method returns an Object[] pretending to be a T[], and the ClassCastException appears later at the caller's assignment, far from the cause. The fix is list.toArray(String[]::new), or passing a Class<T> or an IntFunction<T[]> so the method can create a correctly typed array.

Why this question is asked

This bug is confusing because the error message contradicts our intuition: every element is a String, so why can the array not be a String[]? The answer is the difference between an array's elements and the array object itself, plus the way generics are erased. Interviewers ask it at a mid-senior level because the generic version of the bug is a common mistake in utility code and its failure appears in a completely different place. In this answer, we will recap what reified arrays mean, explain the first ClassCastException, follow the generic method to see where its exception really happens, and fix both cases.

1A Quick Recap: Arrays Know Their Type at Run Time

Every array object carries its component type. A new String[2] is an object of class String[], and a new Object[2] is an object of class Object[], no matter what we put into it. We call arrays reified because this type information exists at run time, and the JVM uses it to check every store into the array.

Generics are the opposite. A List<String> and a List<Integer> are the same class at run time, just ArrayList or whatever implementation was used. The type argument is erased after compilation. So a generic method that has a type parameter T does not know, while it runs, what T is.

2Why the Cast Fails Although Every Element Is a String

Collection.toArray() with no arguments is documented to return an Object[]. ArrayList implements it by copying its internal Object[] storage, so the result is an object whose class is Object[].

Java
List<String> list = new ArrayList<>(List.of("ann", "bob"));
Object[] raw = list.toArray();
System.out.println(raw.getClass().getSimpleName()); // Object[]
String[] names = (String[]) raw;
// ClassCastException: class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.String;

A cast never converts an object; it only checks that the object already is of the target type. The object raw points to is an Object[], and an Object[] is not a String[], because String[] is a narrower type that promises only Strings will ever be stored. The elements inside do not matter: an Object[] that happens to hold Strings today could hold an Integer tomorrow, so the JVM refuses the cast. In the message, [Ljava.lang.Object; is the JVM's internal name for Object[].

As a historical note, Arrays.asList(...).toArray() used to return an array of the original type, which made this cast sometimes work and sometimes fail. Since Java 9 it returns Object[] like every other collection (check older code that relied on the old behaviour).

3The Generic Helper That Fails Somewhere Else

Now consider a helper that seems to solve the problem by casting inside a generic method.

Java
@SuppressWarnings("unchecked")
static <T> T[] toArray(List<T> l) {
return (T[]) l.toArray(); // unchecked: erased to (Object[]), so no check at run time
}
List<String> list = List.of("ann", "bob");
Object[] o = toArray(list); // works: nothing checks the type here
String[] s = toArray(list); // ClassCastException on this line, in the caller
Step throughWhere the unchecked cast really fails
CallertoArray helperList
toArray(list) with T = String
l.toArray()
new Object[] {ann, bob}
(T[]) cast erased: no check
returns the Object[]
hidden cast to String[]: ClassCastException

6 messages in order. Play them, or step through them one at a time.

The bug is in the helper, but the exception is thrown in the caller.

The cast to T[] compiles with an unchecked warning, which tells us the compiler cannot verify it. After erasure, T[] becomes Object[], so the method returns the Object[] without any check. The method looks like it works.

The failure appears at the caller. When we assign the result to a String[], the compiler inserts a hidden cast to String[] at that line, because the caller's code knows T is String. That hidden cast checks the real object, finds an Object[], and throws. The stack trace points at the caller's assignment, not at the helper, so the person debugging looks in the wrong place. If the result is passed through several methods first, the exception can surface far away from where the bad array was created. This is heap pollution: a variable of type T[] refers to an object that is not a T[].

4Fixing Both Cases

To get a String[], someone must create an array whose run-time class is String[]. Since generic code cannot know T, the caller provides the type, either as an array generator or as a Class object.

Java
String[] names = list.toArray(String[]::new); // Java 11 and later
String[] names2 = list.toArray(new String[0]); // every version
static <T> T[] toArray(List<T> l, IntFunction<T[]> generator) {
return l.toArray(generator); // the caller decides the array type
}
static <T> T[] toArray(List<T> l, Class<T> type) {
@SuppressWarnings("unchecked")
T[] arr = (T[]) Array.newInstance(type, l.size()); // a real T[] created by reflection
return l.toArray(arr);
}
String[] a = toArray(list, String[]::new); // [ann, bob], runtime type String[]
String[] b = toArray(list, String.class); // [ann, bob], runtime type String[]

In the Class version, the unchecked cast is now honest: Array.newInstance(String.class, n) really creates a String[], so the cast is true at run time and the warning can be suppressed with a clear conscience. The IntFunction version needs no cast at all, which is why the JDK added toArray(IntFunction) in Java 11.

5Prefer Collections in APIs

The deeper fix is to ask why the code needs a String[] at all. If it is only to pass data between our own methods, returning the List itself, or List.copyOf(list) for an immutable snapshot, avoids generic array creation entirely. Arrays are best kept for internal use, primitive data, or legacy APIs that require them, and the conversion should happen at that boundary with toArray(String[]::new).

6Follow-up questions

Why does the compiler allow the cast to String[] at all?

Because an Object[] variable could legally point to a String[], thanks to array covariance, so the cast might succeed. The compiler allows casts that can succeed for some objects and leaves the check to run time. Only when a cast can never succeed, such as String to Integer, does it reject it at compile time.

Is the @SuppressWarnings on the first helper the real mistake?

Partly. The warning was telling the truth: the cast cannot be verified. Suppressing it without making the cast safe hid the bug. A good rule is to suppress unchecked warnings only on a single statement, with a comment explaining why the cast is actually correct.

Does List.of(...).toArray() return a String[]?

No. Like all collections since Java 9, it returns an Object[] from the no-argument toArray(). Only the toArray(T[]) and toArray(IntFunction) overloads return a typed array.

7Conclusion

In this answer, we saw that list.toArray() always returns an object of class Object[], and because arrays are reified, a cast to String[] fails no matter what the elements are. The generic helper hides the same problem behind an erased, unchecked cast, so it returns an Object[] posing as a T[] and the ClassCastException appears at the caller's hidden cast, far from the cause. The fixes are list.toArray(String[]::new) or toArray(new String[0]), or a helper that takes an IntFunction<T[]> or a Class<T> and creates a real T[] with Array.newInstance, and better still, keeping collections in APIs.

What to say in the interviewAbout 80 seconds aloud

Open with

The first cast fails because toArray() with no arguments always creates a new Object[], and arrays know their type at run time. A cast doesn't convert anything, it only checks the object's actual class, and an Object[] is not a String[], regardless of what's stored in it right now.

Then, if they want more

So it throws ClassCastException even though every element is a String. The generic helper is worse because it hides the problem. The cast to T[] is unchecked: after erasure it's just a cast to Object[], so nothing is checked inside the method, and it returns the Object[] while claiming it's a T[].

The failure only happens at the caller, where the compiler inserts a hidden cast to String[] when we assign the result. So the stack trace points at the caller's line, possibly far from the real bug, which is classic heap pollution. The fix is to let the caller supply the array type: list.toArray(String[]::new) since Java 11, or toArray(new String[0]).

If I need a generic helper, I take an IntFunction<T[]> and pass it to toArray, or take a Class<T> and use Array.newInstance to create a real T[]. And in general I'd rather return collections from APIs, so generic array creation isn't needed.

About this answer

Last updated
12 November 2026
Versions it names
Java 11, Java 9
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Code does Object[] raw = list.toArray(); String[] names = (String[]) raw; and fails with...": https://scrivio-interview-library.netlify.app/java/arrays/b1eb4026fb/