Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 8 of 10 · Java Generics & Type Safety
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 code

Raw type एक generic class/interface है जो अपना type parameter specify किए बिना use होता है, जैसे List की जगह सिर्फ List। यह backward compatibility के लिए है पर सारी compile-time type checking bypass कर देता है।

// 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?