Why java clone() method requires unchecked cast?

25 Views Asked by At

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?

0

There are 0 best solutions below