Solved

Generics in java

Posted on 2014-03-25
6
520 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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Fibonacci challenge 11 84
pairstar challenge 2 42
XML Paring  Error - Premature end of file. 7 57
Free Alternative to JIRA 4 58
I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
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 different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

744 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now