1

This is something I'm pretty sure was already answered a number of times, but I could not find the answer. I have a method accepting Map<Object, Object>, but when I try to assign a Map<TypeA, TypeB> to it, it is not possible. And I cannot even typecast the map for some reason.

This is strange. My thinking about this is that since every class is an Object, every Map of whatever types should also be a Map<Object, Object>.

It seems that my understanding of the subject is incomplete, where am I getting confused?

JohnEye
  • 6,436
  • 4
  • 41
  • 67
  • is there any other doubt you have regarding your question... I will try to modify my answer accordingly. – nits.kk May 13 '18 at 16:26
  • @nits.kk Nah, I just didn't go through my unaccepted questions for a while. I do this every once in a (sometimes long) while. – JohnEye May 14 '18 at 12:56

1 Answers1

3

There is a reason for this behaviour. Let us figure it out in a reverse way.

Let's assume it works (later we will see the ill effects and hence will conclude why it was decided to make it non compiling)

public class Some{
      private Map < Object, Object > map;
      public class setMap(Map < Object,Object > map){
          this.map = map;//considering it was allowed and implicit casting was done.
          this.map.add(1,2);
          this.map.add(new Student(), new Object());
          this.map.add("abcd", new Student());
          this.map.add(new Employee(), new House());
          this.map.add(new Whatever(), new EveryThing());
          // In short now map can hold any object as key and value without promoting any compile error.
     }
     public void setStudentNameMap(){
           setMap(new HashMap < String, Student >());
           // What key value pairs now we expect to be of type while iterating ?
     }
}

In the code above we intent the map to hold key as of type String and value to be of type Student object and hence we went for using generics and provided the type. But does it helped us ? No even we provided the type still later object of any type can be set as key and value which just defies the use of generics.

Just imagine now iterating the map in the method setStudentNameMap(). What would be the type expected for key and value ? String and Student for key and value respectively. But what will we get is first object of type Integer as key and value and so on blowing our application with type cast exceptions

Similar is the reason as why its unsafe to mix non generic collections and maps with generic ones.

As we have seen how useless this would have made generics hence it was decided (as one of the main reason) to make it a compile time error

nits.kk
  • 5,204
  • 4
  • 33
  • 55