【问题标题】:How is void invalid type for method addContact(String name, Integer number) and removeContact(String name)?方法 addContact(String name, Integer number) 和 removeContact(String name) 的无效类型如何?
【发布时间】:2019-09-10 21:59:06
【问题描述】:

我在这两种方法中都遇到了无效类型错误。这两种方法的有效类型可能是什么。

    HashMap<String, Integer> contacts = new HashMap<>();

public void addContact(String name, Integer number) {
    contacts.put(name, number);
}

public void removeContact(String name) {
    contacts.remove(name);
}

【问题讨论】:

标签: java dictionary collections hashmap set


【解决方案1】:

@shubham 请确保您在此处粘贴的代码的 sn-p 未写在 main() 方法中。如果你在一个类中定义你的代码sn-p,它不会有任何编译问题。

import java.util.HashMap;
public class Test1
{

    HashMap<String, Integer> contacts = new HashMap<>();

    public void addContact(String name, Integer number) {
        contacts.put(name, number);
    }

    public void removeContact(String name) {
        contacts.remove(name);
    }

    public static void main (String [] args)
    {
        // Do something
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-14
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多