【问题标题】:Why does Java think that HashMap's methods don't exist? [closed]为什么Java认为HashMap的方法不存在? [关闭]
【发布时间】:2021-11-22 05:10:11
【问题描述】:

我正在为我的编码课程做一个期末项目(这是一个“做任何你想做的事,但包括 HashMapgraph”类型的东西),

但是我的HashMap 不认为“put”方法和“get”方法存在,或者类似的东西。在有get()put() 调用的每一行上(我会在这些行的分号后面加上一个*)它说它期望在. 之后有一个@,期望一个., 之后,预计?; 之后。

我真的很困惑,因为看着我们的课堂示例,我似乎没有做任何与课堂上不同的事情。

任何帮助将不胜感激,谢谢。

这是我的代码:

import java.util.*;

@SuppressWarnings("unchecked")

public class HashMapForFinal {

    public HashMap<String, HashMap<Integer, Integer>> map = new HashMap<String, HashMap<Integer, Integer>>(); 
    Random rand = new Random();
    int randomInt = rand.nextInt(7);
    map.put("correct", new HashMap<Integer, Integer>()); *
    map.get("correct").put(1, 1); *
    map.get("correct").put(2, 2); *
    map.get("correct").put(3, 3); *
    map.get("correct").put(4, 4); *
    map.get("correct").put(5, 5); *
    map.get("correct").put(6, 6); *

    map.put("incorrect1", new HashMap<Integer, Integer>());
    map.get("incorrect1").put(1, 6); *
    map.get("incorrect1").put(2, 5); *
    map.get("incorrect1").put(3, 4); *
    map.get("incorrect1").put(4, 3); *
    map.get("incorrect1").put(5, 2); *
    map.get("incorrect1").put(6, 1); *
    
    map.put("incorrect2", new HashMap<Integer, Integer>()); *
    map.get("incorrect2").put(1, randomInt); *
    map.get("incorrect2").put(2, randomInt); *
    map.get("incorrect2").put(3, randomInt); *
    map.get("incorrect2").put(4, randomInt); *
    map.get("incorrect2").put(5, randomInt); *
    map.get("incorrect2").put(6, randomInt); *
    
}

编辑

感谢 cmets 中的某个人(谢谢),我没有将它放入方法中。

【问题讨论】:

  • 看起来这一切都需要放入一个方法中,而你只是想把它放在一个类的中间。

标签: java hashmap


【解决方案1】:

方法调用确实是正确的,但是它们在错误的位置。您将代码放置在字段和方法应位于的位置,但代码必须在方法内部。像这样:

public class HashMapForFinal {
  public Map<String, Map<Integer, Integer>> map = new HashMap<String, Map<Integer, Integer>>();

  public void foo(){
    // rest of the code goes here
  }
}

另请注意,对于 map 字段的声明,可以(并且更好)使用接口而不是实现类。

【讨论】:

    猜你喜欢
    • 2020-01-04
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 2013-12-18
    • 1970-01-01
    • 1970-01-01
    • 2023-02-05
    相关资源
    最近更新 更多