Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert "Object" to "HashMap" in Java

Here is a example:

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        HashMap<Integer, Integer> a = new HashMap<Integer, Integer>();
        a.put(1,2);
        a.put(2,5);
        Object b = a;
        // Do something here to make the variable "b" become a HashMap
    }
}

I tried this

HashMap<Integer, Integer> c = (HashMap<Integer, Integer>) b;

I get this warning:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Unchecked cast: ‘java.lang.Object’ to ‘java.util.HashMap<java.lang.Integer,java.lang.Integer>’

>Solution :

The warning is expectable in this situation, because such a casting considered as an unsafe operation. From your example it is hard to say why do you need such a cast, maybe you should re-think your code to avoid it. But if there is no other option, you may leave it, because in runtime it will work. You may also consider to suppress the warning for the method or class:

@SuppressWarnings({"unchecked"})
public static void main(String[] args) {
   // your code there
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading