Person无法转换为HashMap <string,person =“”>

时间:2016-11-04 10:44:05

标签: java hashmap

我想我理解错误消息的含义,我有一个Person,并且我正在尝试将其转换为HashMap&lt; String,Person&gt;,但这不是代码所说的?我不明白我做错了什么。当我阅读代码时,我发现没有问题。 我现在已经坚持了一段时间..如果有一些基本的我错过了我很想听到它,因为我没有得到这个错误信息

C

返回personer.put(姓名,人);我得到错误说不兼容的类型:Person无法转换为HashMap&lt;字符串,人物&gt ;;

我也在personer.put上遇到错误(newPerson(line));说找不到合适的方法,但我认为这两个错误是相关的吗?

3 个答案:

答案 0 :(得分:2)

您的代码中存在一些逻辑问题,personer.put(name, person)返回Person而不是HashMap<String, Person>
在您的readFile中,您打开了两次文件

    File file = new File(filnavn);
    Scanner in = new Scanner(new File(filnavn)); // new File(filnavn), you didn't use the file !

我想你想要读取每行中包含人名的文件。
这是你的方式

//Method to read file
public void readFile(String filnavn) throws Exception {
    String line;
    String current; // you didn't use this variable !

    File file = new File(filnavn);
    Scanner in = new Scanner(file);
    while (in.hasNextLine()) {
        line = in.nextLine();
        personer.put(line,new Person(line)); // you don't need the newPerson(String name) method
    }
}

答案 1 :(得分:1)

问题出在这里:

public HashMap<String, Person> newPerson(String name) {
    Person person = new Person(name);
    return personer.put(name, person);
}

这不起作用,因为personer.put返回一个Person而不是一个Map,所以你需要让方法返回一个Person,或者返回一个Personer地图

因此,将其更改为此以返回地图:

public HashMap<String, Person> newPerson(String name) {
    Person person = new Person(name);
    personer.put(name, person);
    return personer;
}

这种方法返回Map,如方法定义所需。

至于construtor你使用你创建的方法返回一个Map,而不是类construtor应该是:

new Person("name");

所以它必须是这样的,假设有一个construtor在Person类中接受一个String:

public void readFile(String filnavn) throws Exception {
    String line;
    String current;

    File file = new File(filnavn);
    Scanner in = new Scanner(new File(filnavn));
    while (in.hasNextLine()) {
        line = in.nextLine();
        personer.put(new Person(line));
    }
}

答案 2 :(得分:1)

添加到地图,然后返回地图。相反,您将返回地图放置操作的结果,而不是地图本身。

相关问题