Solved

Generics in java

Posted on 2014-03-25
6
531 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
  • 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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
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:

777 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