Solved

Generics in java

Posted on 2014-03-25
6
546 Views
Last Modified: 2014-04-29
Generics: This happens at compile-time. The compiler checks for the type correctness of the program and translates or rewrites the code that uses generics into non-generic code that can be executed in the current JVM. This technique is known as “type erasure”. In other words, the compiler erases all generic type information contained within the angle brackets to achieve backward compatibility with JRE 1.4.0 or earlier editions.

I have not understood clearly what it means.

please advise
Any links resources ideas highly appreciated. Thanks in advance
0
Comment
Question by:gudii9
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
6 Comments
 
LVL 35

Accepted Solution

by:
mccarl earned 500 total points
ID: 39954830
This is best explained with a simple example. Say you have a List defined using generics as such...     List<String> stringList;      This basically intends to mean a List that can only hold objects of the String type. However, this constraint is only enforced at compile time, ie. it is the compiler that gives an error if you try to do something like...    stringList.add(new Integer(1));    It will say that you can't put an object of type Integer into a List with generic type String.

The point to this is that when it comes to runtime, there is no constraint enforced that objects in this List have to be Strings, ie. the fact that the List has a generic type of String has been "erased". If you can get around the compiler enforcing the List to only contain Strings, you can still put any object in the List. Consider the following code...
import java.util.ArrayList;
import java.util.List;

public class TestGenerics {
    
    public static void main(String[] args) {
        List<String> stringList = new ArrayList<String>();
        
        stringList.add("Foo");
        stringList.add("Bar");
        
        ((List) stringList).add(new Integer(1));
        
        for (Object item : stringList) {
            System.out.println("Item: " + item);
        }
    }
    
}

Open in new window

The above code will compile perfectly fine (although with a warning about us trying to trick the compiler) producing a .class file that can be executed by the JVM. Even when we do execute the code, it will run perfectly fine, ie. it will execute line 12 with no problems and so the List at this point contains 2 Strings and 1 Integer. The for loop even works printing the 2 Strings and the Integer out to the console.

So we have proven that our List<String> can actually hold non-String objects at runtime.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40005317
Is it is a bug which needs to be resolved in later releases of java? please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40005326
((List) stringList).add(new Integer(1));

How the above line compiled.


If you can get around the compiler enforcing the List to only contain Strings, you can still put any object in the List.

How did we get around compiler enforcement.
I do got output as below
Item: Foo
Item: Bar
Item: 1


Please advise
0
Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

 
LVL 35

Expert Comment

by:mccarl
ID: 40005630
((List) stringList).add(new Integer(1));

How the above line compiled.
Basically, it is saying to take "stringList" which was originally defined as "List<String>" but cast it to be a plain "List". And then, because it is (temporarily) a plain List object, then we can call the .add() method and pass an Integer object.

How did we get around compiler enforcement.
Exactly by what I just said above. Normally, stringList is a "List<String>" and so the compiler ensures that we only add String objects. But by casting it as a plain "List", we can now add ANY type of object to it.

I do got output as below
Item: Foo
Item: Bar
Item: 1
That is correct. It is showing you that the list contains both Strings and Integers.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40006972
I see the trick.

((List) stringList).add(new Integer(1));
       


can i cast instead to List of some other type other than String say custom object CUSTOMER like

((List<CUSTOMER>) stringList).add(new Integer(1));
       
Please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40020409
Please advise
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Maven Project: Hibernate Dependencies Conflict 10 95
SHA2 certs for IIS AND Java? 2 136
Notify sent to other threads in Java 9 54
java mysql insert application 14 68
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question