0

This code snippet:

    public static void main(String[] args) {
        HashMap<Integer, String> mif = new HashMap<>();
        mif.put(2, "haha");
        mif.put(3, "hello");
        mif.put(1, "hi");
        HashMap<Integer, String> mifClone = mif.clone(); // compile error

The last line doesn't compile, saying that:

Type mismatch: cannot convert from Object to HashMap<Integer,String>

So I changed to

        HashMap<Integer, String> mifClone = (HashMap<Integer, String>)mif.clone(); // warning

This time it becomes a warning:

Type safety: Unchecked cast from Object to HashMap<Integer,String> Java(16777761)

My question:

(1) Java compiler knows that mif has specified type, why "clone()" still returns an "Object" instead of HashMap<Integer, String> type?

(2) How to fix the "unchecked" warning, without suppressing it?

Troskyvs
  • 7,537
  • 7
  • 47
  • 115
  • 1) It does NOT know that `clone` returns a `HashMap`. `Object` is not a generic type, and the return type of `clone()` is `Object`. Check the javadoc. Note that if they changed this, it would most likely break millions of existing Java programs. – Stephen C Jun 18 '22 at 02:13
  • 2) Use `new HashMap<>(mif)` instead. As a general rule you should avoid using `clone()`, especially if there is a more specific alternative ... with better defined semantics. (Read the javadoc for `clone` to get a gist of what I mean about semantics ...) – Stephen C Jun 18 '22 at 02:15
  • 1
    1a) Note that `HashMap` is not `final`. So someone could declare a subclass of `HashMap` where `clone` returned (say) an `Integer` rather than a `HashMap` subclass. The cast is necessary. – Stephen C Jun 18 '22 at 02:20
  • @StephenC This explanation really makes sense. – Troskyvs Jun 18 '22 at 02:29
  • Yes. But 1) trumps 1a). The Java compiler does not know anything about how the class libraries choose to implement `HashMap.clone()`. All it knows is that the `HashMap` API says `Object` is the return type. See https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#clone-- – Stephen C Jun 18 '22 at 02:41

0 Answers0