在Java中将“Object”转换为“HashMap”

问题描述 投票:0回答:1

这是一个例子:

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
    }
}

我试过这个

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

我收到此警告:

未经检查的转换:'java.lang.Object' 到 'java.util.HashMap'

java object hashmap
1个回答
0
投票

在这种情况下出现警告是可以预料的,因为铸造这样的铸件被认为是不安全的操作。从你的例子中很难说为什么你需要这样的强制转换,也许你应该重新考虑你的代码来避免它。但如果没有其他选择,你可以保留它,因为在运行时它会起作用。您还可以考虑抑制方法或类的警告:

@SuppressWarnings({"unchecked"})
public static void main(String[] args) {
   // your code there
}
© www.soinside.com 2019 - 2024. All rights reserved.