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
Solved

Generics in java

Posted on 2014-03-25
6
536 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
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.

 
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

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
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 scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

828 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