Interview question
What are raw types in Java, and why should you avoid them? Java में raw types क्या हैं, और इनसे क्यों बचना चाहिए?
Answer
A raw type is a generic class or interface used WITHOUT specifying its type parameter, e.g. using List instead of List<String>. It exists for backward compatibility but bypasses all compile-time type checking.
// Raw type usage - legal but discouraged
List rawList = new ArrayList(); // no type parameter specified
rawList.add('Hello');
rawList.add(42); // no compile error - mixed types allowed!
rawList.add(true);
for (Object o : rawList) {
// must cast manually and carefully, error-prone
if (o instanceof String) {
String s = (String) o;
}
}
// Parameterized type - the correct, safe approach
List<String> typedList = new ArrayList<>();
typedList.add('Hello');
// typedList.add(42); // COMPILE ERROR - caught immediately
// Mixing raw and generic types causes 'unchecked' warnings
List<String> list = new ArrayList<>();
List rawRef = list; // raw reference to a generic list
rawRef.add(42); // compiles with an 'unchecked' warning, but corrupts 'list'
String s = list.get(0); // ClassCastException at RUNTIME - 42 isn't a String!
// The compiler emits: 'unchecked call to add(E) as a member of the raw type List'
// warnings like this should NEVER be ignored
// Rule of thumb: ALWAYS specify a type parameter (or use <> diamond
// operator to infer it) - raw types exist ONLY for legacy code compatibility
// and should never appear in new codeRaw type एक generic class/interface है जो अपना type parameter specify किए बिना use होता है, जैसे List
// Raw type usage - legal पर discouraged
List rawList = new ArrayList();
rawList.add('Hello');
rawList.add(42); // कोई compile error नहीं!
rawList.add(true);
for (Object o : rawList) {
if (o instanceof String) {
String s = (String) o;
}
}
// Parameterized type - सही तरीका
List<String> typedList = new ArrayList<>();
typedList.add('Hello');
// typedList.add(42); // COMPILE ERROR
// Raw और generic types mix करने से 'unchecked' warnings
List<String> list = new ArrayList<>();
List rawRef = list;
rawRef.add(42); // 'unchecked' warning के साथ compile, list corrupt होती है
String s = list.get(0); // ClassCastException RUNTIME पर!
// नियम: हमेशा type parameter specify करें (या <> diamond operator)
// raw types सिर्फ legacy code compatibility के लिए हैंWas this answer clear?