在HashMap< K , V >中, K 或 V 可以是自定义类对象,而不是包装类对象??
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Test test=new Test();
HashMap<String, test> a= new HashMap<String, test>();
}
}
发生错误:无法将测试解析为类型。
提前致谢。 问候。
答案 0 :(得分:1)
在hashmap中,是的,您可以将自定义类型包含为键/值对。
但不应该是object
,它必须明确为type
。
表示您可以提及的class
对于自定义类型变为type
。
例如,
您可以将String类型变量定义为String s = "abc";
现在 如果我们试着写下面的话
HashMap<String, s> a= new HashMap<String, s>();
它不会编译,因为's'
不是类型而不是String
类型的对象,
因此它应该在下面
HashMap<String, String> a= new HashMap<String, String>();
所以你的代码如下
Test test=new Test();
HashMap<String, test> a= new HashMap<String, test>();
应该成为
Test test=new Test();
HashMap<String, Test> a= new HashMap<String, Test>();
答案 1 :(得分:0)
HashMap属于通用类型。因此,我们可以传递任何类型的对象作为关键&amp;值。
但是如果你想指定Key&amp;的类型您可以通过编写类名来指定HashMap中的值。
但是在您的代码中,您已使用对象测试来指定对象类型。 所以你应该写这样的东西
HashMap map = new HashMap(); map.put(&#34; string1&#34;,new Test());