Hi
what is the difference between following 2 loops?
when is the casting done, i.e. can an object be casted by applying
this generaic 'tags'
thanks for help in advance
Map<String,String> aMap = new HashMap<String,String>();
for(Map.Entry<String,String> e: aMap.entrySet()){
System.out.print( e.getKey(), e.getValue() );
}
and
for(Map.Entry e: amap.entrySet()){
System.out.print( e.getKey(), e.getValue() );
}
Daniel Pitts - 30 Apr 2007 22:57 GMT
On Apr 30, 2:52 pm, "sak...@gmail.com" <sak...@gmail.com> wrote:
> Hi
>
[quoted text clipped - 17 lines]
>
> }
The second loop gives you an untyped Map.Entry e. There is no casting
done. e.getKey()'s signature would appear as an Object, same with
e.getValue().
You are better off using the first version. It specifies exactly what
you want, an Entry with a String key and a String value.
Hendrik Maryns - 02 May 2007 12:23 GMT
sakcee@gmail.com schreef:
> Hi
>
[quoted text clipped - 15 lines]
> System.out.print( e.getKey(), e.getValue() );
> }
The first is generic, the second isn’t. But the print() method cares
not. It just invokes (indirectly) the object’s toString() method, which
both have, generic or not.
It would make more sense if you really did something with the key and
value, e.g. assign them to a local parameter. Then you’ll see that
Map<String,Integer> aMap = new HashMap<String,Integer>();
for(Map.Entry<String,Integer> e: aMap.entrySet()){
String key = e.getKey();
Integer value = e.getValue();
// do some more
}
is allowed, whereas
for(Map.Entry e: amap.entrySet()){
String key = e.getKey();
Integer value = e.getValue();
// do some more
}
is not. To answer your question: generics was introduced to get rid of
all the unnecessary casting. So there is no casting there. The
compiler just statically checks that the types are right.
Summary: it is not that casting is done by the generic ‘tags’, but that
the generics /avoid/ casting.
H.
- --
Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html