$show=/label

Raw type Generics in Java - Working Examples

SHARE:

Raw Type is part of Java Generics. Raw Type is If any generic class reference or instance is created without mentioning the proper Type fo...

Raw Type is part of Java Generics. Raw Type is If any generic class reference or instance is created without mentioning the proper Type for the Generic type. Reference indicates to Class or Interface.

Generics in Java

Generics naming conventions and rules

Generics main aim to provide tighter type checks at compile time.

Raw type in Java Generics with Examples




Please go through the following basic example program.


Java Raw Type Example:



package com.adeepdrive.generics;

public class RawTypeExample {

    public static void main(String[] args) {

        RawType<String> genericObj = new RawType<String>();
        genericObj.setT("Generic Object");
        System.out.println("Generic Object created String type. It's value : " + genericObj.getT());

        RawType rawType = new RawType(); // Legal, but it will give warnings.
        rawType.setT(new Integer(20));
        System.out.println("Raw Type Generic Object creage. It's value : " + rawType.getT());
    }
}

class RawType<T> {
    T t;
    public T getT() {
        return t;
    }

    public void setT(T t) {
        this.t = t;
    }
}

Output:

Generic Object created String type. It's value : Generic Object
Raw Type Generic Object creage. It's value : 20

In the above program, we have created a generic class "RawType" and then created an object for RawType by passing generic type String. Which is legal against Generic rules.

Second, Created another object for RawType class but did not pass any Generic type to it. That means we can set any value to it. That can be String, Integer, List or any class. In our example, we passed Integer instance. Compiler will give warning but safe.

Oracle Java Raw Types Guide.

 

Reassigning RawType instances example:



package com.adeepdrive.generics;
public class RawTypeExample2 {
    public static void main(String[] args) {

        RawType rawTypeObj1 = null;
        rawTypeObj1 = new RawType();
        rawTypeObj1.setT(new Integer(20));
        System.out.println("rawTypeObj1 value : " + rawTypeObj1.getT());
    
        RawType rawTypeObj2 = new RawType();
        rawTypeObj2.setT(new Integer(20));
        System.out.println("rawTypeObj2 value : " + rawTypeObj2.getT());
      
        rawTypeObj1 = rawTypeObj2;
        System.out.println("rawTypeObj1 value : " + rawTypeObj1.getT());
    }
}

Output:

rawTypeObj1 value : 20
rawTypeObj2 value : 20
rawTypeObj1 value : 20

The above program compiles and runs fine.

RawType rawTypeObj1 = null;
rawTypeObj1 = new RawType();
       
First, created raw type reference rawTypeObj1 and object without passing type to it. This means, compiler does not know what type should be added to it. So, we can add any type of object. Compile will not give error at this point. Compilation is fine.

Next, create new object by passing type as String while creating object for RawType.
RawType rawTypeObj2 = new RawType<String>();

new RawType<String>(): This object knows about String type but reference rawTypeObj2 has no idea about type. In next line, we have set the integer. Which is perfectly right. This is similar to the rawTypeObj1. we can set any object to rawTypeObj2. Here also no error.

Error or Invalid Example:


RawType<String> rawTypeObj2 = new RawType<String>();
rawTypeObj2.setT(new Integer(20));

In the above example, We have created an object with generic type as String (Reference side and object creation side). But next, set Integer object to it which gives compile time error message as following.

The method setT(String) in the type RawType<String> is not applicable for the arguments (Integer)

Tricky Example:


package com.adeepdrive.generics;

public class RawTypeTricky {
    public static void main(String[] args) {
        Color<String> colorOne = new Color();

        Color colorTwo = colorOne;
        colorTwo.setType(100);
         System.out.println("colorTwo value : " + colorTwo.getType());
    }
}

class Color<T> {
    T type;
     public T getType() {
        return type;
    }

    public void setType(T type) {
        this.type = type;
    }
}

This is tricky, Guess the output of this program.

Program compile and runs fine but will give warnings.
Type safety: The expression of type Color needs unchecked conversion to conform to Color<String>

Output:

colorTwo value : 100

What is difference between ArrayList and ArrayList<?>?


If we create object using these two methods, both seems to be adding anything is allowed.

ArrayList list = new ArrayList();
list.add("Jhon");
list.add(10);
list.add(new HashMap());

Above code is valid.

ArrayList<?> list2 = list;
System.out.println("list2 size : "+list2.size());
       
Output:

list2 size : 3

list2.add("Cena");
But when add any object or value to list2 then will give compile time error. Because list2 is pointing to wildcard (?) which means list2 does not know what type of objects to be added to it.

Here, list2 becomes read only arraylist.

Most of the cases and as per the collection classes usage, wild card(?) is used with extends keyword as below.

ArrayList<? extends Number> list = new ArrayList<Integer>();

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,31,ArrayList,16,Arrays,2,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,4,Collections,20,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,5,Core Java,72,Corona India,1,Create,2,CSS,1,Date,2,Date Time API,3,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,2,Fast,1,Files,9,Float,1,Font,1,For examples,1,For loop examples,1,For Loop in Java,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HTML,2,HttpClient,2,Immutable,1,Inner for loops,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,28,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,java 5 For loop,1,Java 8,47,Java 9,1,Java Design Patterns,1,Java Files,1,Java for loop,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,Nested for loop,1,Nested for loop examples,1,New Features,1,Operations,1,Optional,4,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Softwares,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Stream,2,Streams,11,String,48,String Programs,8,String Revese,1,Swing,1,System,1,Tags,1,Threads,8,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Raw type Generics in Java - Working Examples
Raw type Generics in Java - Working Examples
https://3.bp.blogspot.com/-AjR94AAP0Lw/WfIyKXJsODI/AAAAAAAAAu4/ExeUSFCkEm8hBOVLNOsLVIeZvhiaiBgWACLcBGAs/s320/10%2BRaw%2Btype%2Bin%2BJava%2BGenerics%2Bwith%2BExamples.jpg
https://3.bp.blogspot.com/-AjR94AAP0Lw/WfIyKXJsODI/AAAAAAAAAu4/ExeUSFCkEm8hBOVLNOsLVIeZvhiaiBgWACLcBGAs/s72-c/10%2BRaw%2Btype%2Bin%2BJava%2BGenerics%2Bwith%2BExamples.jpg
JavaProgramTo.com
https://www.javaprogramto.com/2017/10/raw-type-in-java-generics-with-examples.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2017/10/raw-type-in-java-generics-with-examples.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content