gpt4 book ai didi

java - 使用泛型的 Hashmap getter setter

转载 作者:行者123 更新时间:2023-12-02 05:23:26 28 4
gpt4 key购买 nike

我有以下两个类(class)

动物类

class Animal {

Map<String, A> data = new HashMap <String, A>();

public void setValue(HashMap<String, ?> val)
{
this.data = val;
}
public Map getValue()
{
return this.data;
}
}

狗类

class Dog extends Animal {

public void index()
{
Map<String, A> map = new HashMap<String, A>();

map.put("name", "Tommy");
map.put("favfood", "milk"); // want to pass Lists, Integers also
setValue(map);
}
}

正如您从上面的代码中看到的,我正在尝试使用 index 方法中的键设置一些值,但是我在两个文件中都收到来自 eclipse 的错误警告。错误消息是:

在狗类文件中:

Multiple markers at this line
- A cannot be resolved
to a type
- A cannot be resolved
to a type

在动物类文件中:

Multiple markers at this line
- A cannot be resolved to a type
- A cannot be resolved to a type
- Incorrect number of arguments for type Map<K,V>; it cannot be parameterized with arguments
<HashMap<String,A>>

HashMap 中键的数据类型始终是字符串,但值的数据类型是随机的,因此我尝试使用泛型。

来自 PHP 背景的我仍然无法掌握 Java 泛型的概念。你能告诉我我的代码哪里有错误吗?

最佳答案

虽然这种设置不是理想的方法,但一种解决方案是将您的 map 设为 <String, Object>通用类型。这样你就可以把你想要的任何东西放入Object部分。然而,将这些信息撤回会很痛苦。这就是我对你们类(class)变化的看法。

class Animal {

Map<String, Object> data = new HashMap <String, Object>();

public void setValue(Map<String, Object> map)
{
this.data = map;
}
public Map<String, Object> getValue()
{
return this.data;
}
}

class Dog extends Animal {

public void index()
{
Map<String, Object> map = new HashMap<String, Object>();

map.put("name", "Tommy");
map.put("favfood", "milk"); // want to pass Lists, Integers also
setValue(map);
}
}

关于java - 使用泛型的 Hashmap getter setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26306147/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com