HashMap中。使用自定义类型作为值

时间:2016-04-07 12:19:26

标签: java hashmap

我有类Computer,想要使用Computer作为value的类型,而不是String。但是我收到了一个错误:

  

错误:(22,36)java:不兼容的类型:java.lang.String不能   转换为com.example.lesson18.Computer

public class Main {
private static Map<Integer, Computer> catalogComputersMap;

public static void main(String[] args) {
    catalogComputersMap = new HashMap<Integer, Computer>();
    ComputerStore cs = new ComputerStore();
    catalogComputersMap.put(1, "2 x 1.6 GHz, 4 GB, 512 GB, GeForce 210, 350 Watt");
    catalogComputersMap.put(2, "2 x 3.2 GHZ, 8 GB, 1 TB, Radeon R7 370, 550 Watt");

我在Computer类中生成了equals()和hashCode()(这是我需要的吗?)但结果保持不变。工作代码必须与<Integer, Computer>无关。

4 个答案:

答案 0 :(得分:2)

您将String放在地图中作为值。

您必须使用您希望对象拥有的值创建计算机对象。我不知道你的计算机对象是什么样的,但如果它有一个带字符串的构造函数,代码看起来就像这样

Computer computer = new Computer("2 x 1.6 GHz, 4 GB, 512 GB, GeForce 210, 350 Watt");
catalogComputersMap.put(1, computer);

答案 1 :(得分:1)

但是在这一行:

catalogComputersMap.put(1, "2 x 1.6 GHz, 4 GB, 512 GB, GeForce 210, 350 Watt");

您正在传递String作为第二个参数而不是计算机对象。您应该通过一台计算机来完成这项工作。

答案 2 :(得分:0)

您正在尝试使用(int,String)参数调用方法,其中方法需要(int,Computer)参数。如果您的Computer类具有带String参数的构造函数,则可以传递给put方法。

catalogComputersMap = new HashMap<Integer, Computer>();
ComputerStore cs = new ComputerStore();
catalogComputersMap.put(1, new Computer("2 x 1.6 GHz, 4 GB, 512 GB, GeForce 210, 350 Watt"));
catalogComputersMap.put(2, new Computer("2 x 3.2 GHZ, 8 GB, 1 TB, Radeon R7 370, 550 Watt"));

答案 3 :(得分:0)

您尝试传递字符串&#34; 2 x 1.6 GHz,4 GB,512 GB,GeForce 210,350瓦特&#34;作为一个值而不是计算机。您的计算机类必须是这样的:

public class Computer {

private String info;

public void setInfo(String info){
this.info = info;
}

public String getInfo (){
return this.info;
}

public Computer (String info){
this.info = info;
}
}

然后:

    public static void main(String[] args) {
       Map<Integer, Computer> catalogComputersMap = new HashMap<Integer, Computer>();

        catalogComputersMap.put(1, new Computer("2 x 1.6 GHz, 4 GB, 512 GB, GeForce 210, 350 Watt"));
        catalogComputersMap.put(2, new Computer("2 x 3.2 GHZ, 8 GB, 1 TB, Radeon R7 370, 550 Watt"));
}
相关问题