본문 바로가기

Java/__Base

Java Programming - Why this warning comes when i use Generics in java1.5

Why this warning comes when i use Generics in java1.5?   

"The cast fromObject to List<String> is actually checking against the erased type of List"

I m getting this warning whenever I am fetching any List<String> from a
Map object.

headerList = (List<String>)listMap.get("headerList");

Re: Why this warning comes when i use Generics in java1.5?   
The cast fromObject to List<String> is actually
checking against the erased type of List"

I m getting this warning whenever I am fetching any
List<String> from a
Map object.

headerList = (List<String>)listMap.get("headerList");
Assuming the following code (or something similar) is before the line you posted
    HashMap<String, List<String>> listMap; 
    ArrayList<String> headerList;
    //fill in map and some other stuff


all you have to do is
    headerList = listMap.get("headerList");

because ALL the values in the listMap MUST be List<String> objects

The warning/error tells you that you're trying to cast against a "generic type" which is actually erased when the code is compiled. Remember that generics are only compiletime checks. The cast should refer to a runtime type (generics are not runtime types). I hope I made myself clear. Feel free to ask any further doubts and even better, read the [url=http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf] Tutorial[/url]

Re: Why this warning comes when i use Generics in java1.5?   
actually I have declared HashMap object like this only
Map listMap = new HashMap();
bec I am expecting List, String, Object in it. So I can't make it type Specific.
But the List i m stroing in the Map object is generic.

Map listMap = getTitleCaseHeaderList();
List<String> headerList = (List<String>)listMap.get("headerList"); //warning


Map getTitleCaseHeaderList()
{
Map m = new HashMap();
List<String> headerList = new ArrayList<String>();
headerList .add("XYZ");
m.put("headerList",headerList );
m.put("msg","Done");
m.put("isError",false);
}