ProgrammingVery hardGATE CS · TCS NQT Prime · Product Company SDE
Why can a generic method not simply write `new T[10]` for a type parameter T in Java?
- A. After erasure, the compiler has no concrete runtime type for T, and array creation needs a known component type at run time to set up the array's type tag
- B. Because arrays are a deprecated feature of the language
- C. Because T is erased to Object, and even Object[] cannot ever be created
- D. Because generics forbid the use of arrays for unrelated security reasons
Correct answer: A. After erasure, the compiler has no concrete runtime type for T, and array creation needs a known component type at run time to set up the array's type tag
Since T's actual type is erased, the JVM would not know what runtime array type to create for `new T[]`, so Java disallows it directly (workarounds use Object[] with an unchecked cast, or reflection).
More OOP with C++ and Java questions
- java void f(int x) { System.out.print("int"); } void f(Integer x) { System.out.print("Integer"); } void f(Object... x) {…
- Why does adding a brand-new virtual function to a base class not increase the size of each object in that hierarchy (assuming objects…
- Which java.util.function functional interface best fits a lambda that takes one argument of type T and returns a boolean?
- A base class method is declared final in Java. What does this guarantee about calls to it through a base-class reference, regardless of…
- cpp struct S { int a, b; S(int x) : b(x), a(b) { } }; int main() { S s(5); cout << s.a << " " << s.b; } Members a and b are declared in…
- What does List<? super Integer> allow, in contrast to List<? extends Integer>?