【问题标题】:Type HashMap does not take parametersHashMap 类型不带参数
【发布时间】:2015-11-11 09:54:17
【问题描述】:

我正在关注this video 关于 Java 中的 HashMap。它有below code

// Create the HashMap
HashMap<String,String> hm = new HashMap<String, String>();

// Put data
hm.put("Katie", "Android, WordPress");
hm.put("Magda", "Facebook");
hm.put("Vanessa", "Tools");
hm.put("Ania", "Java");
hm.put("Ania", "JEE");    // !! Put another data under the same key, old value is overridden

// HashMap iteration
for (String key: hm.keySet())
    System.out.println(key+":"+hm.get(key));

所以我写了下面的代码,用它来练习HashMap(几乎相同的代码)

package hashmap;
import java.util.*;

public class HashMap {

    public static void main(String[] args) {

        HashMap<String,String> hm = new HashMap<String, String>();

        hm.put("Katie", "Android, WordPress");
        hm.put("Magda", "Facebook");
        hm.put("Vanessa", "Tools");
        hm.put("Ania", "Java");
        hm.put("Ania", "JEE");   

    }
}

但是类没有编译给出错误“Type HashMap不带参数”所以我搜索了我got this的答案

一个答案说

两个可能的错误:

您使用的是 JDK 1.4

您导入了 java.util.Map 以外的其他内容

所以我导入了java.util.Map,但 netbeans 给出了这个错误并说导入没有使用。然后我java.util.*; 但结果是一样的。我不知道这是否是我的 IDE 错误的新手错误。

我在 windows 8.1 中的 jdk 1.8 和 Netbeans 8.0.2

【问题讨论】:

  • Nvm。你用你的类的命名来掩盖 HashMap 。完全忽略了这一点。感谢@manouti

标签: java shadowing


【解决方案1】:

你将你的班级命名为HashMap,这会影响java.util.HashMap。只需将其重命名为其他名称即可。

【讨论】:

  • 或在创建地图时使用java.util.HashMapnew java.util.HashMap&lt;String, String&gt;();,但不建议这样做
  • @Gaël 确实,但重命名要好得多。
  • 知道了提前谢谢
【解决方案2】:

您的public class HashMap 自定义类隐藏了java.util.HashMap,并且您的自定义HashMap 不是通用的,因此new HashMap&lt;String, String&gt;() 对您的自定义类无效。

【讨论】:

  • 知道了 提前谢谢:)
【解决方案3】:

我建议不要使用与 HashMap 相同的类名,因为它是 Java 中 Map 技术的实现,并且在每个循环中也使用 Map.entry 接口作为对象。我希望下面的代码能帮助一些新的 HashMap 小动物。

import java.util.*;
public class QueQue {
public static void main(String[] args) {
    HashMap<String, Integer> hm = new HashMap<String, Integer>();
    hm.put("Peter", 10);
    hm.put("Nancy", 8);
    hm.put("Lily", 9);

    for (Map.Entry<String, Integer> x : hm.entrySet())//entrySet()=Returns a set of all the entries in the map as Map.Entry objects.
    {
        System.out.println(" The String Value in Hashmap is " + x.getKey());
      System.out.println(" The Integer Value in Hashmap is " +x.getValue());
    }
 }
      }

【讨论】:

    【解决方案4】:

    使用现有的JavaType,对于那些想要使用地图属性的人

    {
        "existingJavaType": "java.util.Map<String, String>",
        "additionalProperties": {
            "type" : "string"
        }
    }
    

    【讨论】:

      【解决方案5】:

      我将我的文件命名为 HashMap,我将其更新为它解析的其他名称

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 2023-03-15
      • 2014-11-30
      • 2021-01-31
      • 2018-05-07
      • 1970-01-01
      • 2015-08-19
      • 1970-01-01
      • 1970-01-01
      • 2014-12-16
      相关资源
      最近更新 更多