0
import java.util.*;
public class FinalHashMap {
   private static Integer x = new Integer(3);
   private static final Map map = new HashMap();
   public static void main(String[] args) {
      map.put("param1","value1"); // no error
      map.put("param2","value2"); // no error
      System.out.println(map);
      x = 4; //error
      System.out.println(x);
   }
}

For the above code I get the error for modifying integer but I don't get any error for modifying the HashMap.

Dhruvit
  • 1
  • 2
  • Because `final` refers to the value of the variable (which in the case of an object is its reference), not the object it points to. If `Integer` had modifiable members you could modify that too. – Federico klez Culloca Oct 07 '22 at 13:17
  • Beware that usage of *row type* is discouraged, since Java 1.5 we have generics. Your map should be of type `Map`. And constructor of `Integer` is deprecated. – Alexander Ivanchenko Oct 07 '22 at 13:21
  • And by the way, there's a substantial difference between `map.put("param1", "value1")` and `x = 4`. One is a method call, the other is an assignment. Try `map = new HashMap()`. (leaving aside the use of raw types correctly pointed out by the other commenter). You'll notice you can't do that. – Federico klez Culloca Oct 07 '22 at 13:23
  • @FedericoklezCulloca, please correct me if I'm wrong. for static final Integer, object reference is not created instead a variable is assigned on the other hand for HashMap, object is created and its reference is not getting changed. – Dhruvit Oct 07 '22 at 13:30
  • @Dhruvit *"for static final Integer, object reference is not created instead a variable is assigned"* if you mean when you do `x = 4` then no, that's effectively like doing `x = new Integer(4)` because of [autoboxing](https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html). If that's not what you meant please clarify. – Federico klez Culloca Oct 07 '22 at 13:54
  • 1
    You just need to remove the phrases “*[when] declared as static final*” from your question to get the answer “*Integer is non-modifiable but Map is modifiable*”. – Holger Oct 10 '22 at 09:21

0 Answers0