Raw Types

Java-Raw Types

Raw Types

Although the compiler treats different parameterizations of a generic type as different types (with different APIs) at compile time, but only one real type exists at runtime. For example, the class of Gen<Integer> and Gen<String> share the plain Java class Gen :

Raw Types

Gen is called the raw type of the generic class. Every generic has a raw type. It is the degenerate, “plain” Java form from which all of the generic type information has been removed and the type variables replaced by a general Java type ike Object. You can use the generic type name by itself to define variables. For example :

Raw Types

This creates a variable with the name rgen that is of type Gen from the Gen<T> generic type. This type that results from eliminating the parameters from the generic type is referred to as a raw type. When generics were introduced into the language, the language designers decided that in order to maintain compatibility with pregenerics code, they would need to allow the use of raw types. However, the use of raw types is strongly discouraged for newer (post–Java 5) code, so compilers will generate a raw type warning if you use them and you lose all the safety and expressiveness benefits of generics. For example, the rgen.setT() method accept any type of argument and explicit cast are necessary when the call of rgen.getT() method :

Raw Types

Program

Raw Types

Program Source

class Gen<T> {
    
    private T t1;

    void setT(T t) {
        t1 = t;
    }

    T GetT() {
        return t1;
    }
}

public class Javaapp {

    public static void main(String[] args) {

        Gen rgen = new Gen();
        
        rgen.setT("Ten");
        String s = (String)rgen.GetT();
        rgen.setT(20);
        Integer i = (Integer)rgen.GetT();
        rgen.setT(30f);
        Float f = (Float)rgen.GetT();
        
        System.out.println("s -> "+s);
        System.out.println("i -> "+i);
        System.out.println("f -> "+f);
    }
}

Leave a Comment