(java@oneshot)logo/  logo/  logo/  logo/


 

Java Tutorial » Generics » Generics Basics  
12.1.9.Raw Types and Legacy CodePrevious/Next

To handle the transition to generics, Java allows a generic class to be used without any type arguments. This creates a raw type for the class.

// Demonstrate a raw type.
class Gen<T> 
  T ob;
   
  Gen(T o) { 
    ob = o; 
  
 
  T getob() { 
    return ob; 
  

 
public class MainClass 
  public static void main(String args[]) { 
    Gen<Integer> iOb = new Gen<Integer>(88)
    Gen<String> strOb = new Gen<String>("Generics Test")
 
    Gen raw = new Gen(new Double(98.6));

    // Cast here is necessary because type is unknown.
    double d = (Doubleraw.getob();
    System.out.println("value: " + d);

    strOb = raw; // OK, but potentially wrong
    String str = strOb.getob();  
  
  // This assignment also overrides type safety.
  raw = iOb; // OK, but potentially wrong
  d = (Doubleraw.getob()
    
  
}
Exception in thread "main" value: 98.6
java.lang.ClassCastException: java.lang.Double
  at MainClass.main(MainClass.java:26)
12.1.Generics Basics
12.1.1. Life without Generics
12.1.2. What Are Generics? A Simple Generics Example
12.1.3. Generics Work Only with Objects
12.1.4. A Generic Class with Two Type Parameters
12.1.5. Introducing Generic Types
12.1.6. Working with generic List
12.1.7. Nested generic type
12.1.8. A generic type can accept more than one type variables.
12.1.9. Raw Types and Legacy Code