1

What is the [practical] difference between casting at line 1 & line 2 here, considering Java 6 :

if (obj instanceof HashMap) {
    HashMap meta = (HashMap) obj; // line 1, raw-type warnings
    // vs
    HashMap<?, ?> meta = (HashMap<?, ?>) obj; // line 2, no warnings
    // ..
}

Why would someone go for line 2 (no warnings, type-safe), but seems that casted map can not be used in a meaningful way (i.e., put()/get()) ?

kiruwka
  • 9,250
  • 4
  • 30
  • 41
  • possible duplicate of [Difference between an unbound wildcard and a raw type](http://stackoverflow.com/questions/14242174/difference-between-an-unbound-wildcard-and-a-raw-type) – Konstantin Yovkov Dec 05 '13 at 08:28
  • @kocko thanks, but that question in fact answers `HashMap vs HashMap,?>`, still useful, but I was curios about raw type comparison. In the code above you can not do anything useful with map on line 2, so why would some one use that ? – kiruwka Dec 05 '13 at 08:35

3 Answers3

6

HashMap = HashMap<Object, Object> != HashMap<?, ?>

HashMap<?, ?> m1 = new HashMap<Object, Object>();
m1.put("foo", "bar");    // ERROR!!

HashMap<Object, Object> m2 = new HashMap<Object, Object>();
m2.put("foo", "bar");    // OK

HashMap m3 = new HashMap<Object, Object>();
m3.put("foo", "bar");   // WARNING (should be parameterized)

if you are going to use only HashMap.get() there will be no "pratical" difference.

Michele Mariotti
  • 7,372
  • 5
  • 41
  • 73
  • +1, but a little more description about the WARNING is always helpful :) – Sage Dec 05 '13 at 08:41
  • yes, - compiler will make sure no one puts in Map,?> accidently, looks like a good reason to go for wildcards to provide read-only access to the map. +1 and accepted. – kiruwka Dec 05 '13 at 08:52
1

HashMap and HashMap<k,V>.

First HashMap is generic and second one is specific to type (Key as well value). In first HashMap you can put any generic object where as second one is specific to type.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
1

The HashMap come out from the seocnd line is (nearly) read-only, you cannot add anything to it because of the wildcard. In the first you can add all since it is translated by the compliler as:

HashMap<Object, Object> map: 
arjacsoh
  • 8,932
  • 28
  • 106
  • 166