【问题标题】:HashMap<> error. Illegal start of typeHashMap<> 错误。非法开始类型
【发布时间】:2014-09-22 09:31:25
【问题描述】:

每当我尝试编译这个函数时,它都会在第 10 行给出一个错误 --> ErrorMessage : CandidateCode.java.10: static HashMap hm = new HashMap() 类型的非法开始; 1 个错误 我正在尝试在网站的编译器上编译它,但是当我使用 netbeans 时它完全可以正常工作。

import java.util.*;

public class CandidateCode {

    static int rep, total = 0, sum = 0, i = 0, j = 0;
    static HashMap<Integer, Integer> hm = new HashMap<>();
    static ArrayList<Integer> al;

    public static int DistributingMedals(int input1, int[] input2, int[] input3, 
                                         int[] input4, int input5) {

        //Write code here
        for (i = 0; i < input1; i++) {
            int start = input3[i];
            int end = input4[i];
            int count = input2[i];
            for (j = start; j <= end; j++) {
                try {
                    sum = hm.get(j);
                } catch (Exception e) {
                    e.getMessage();
                    sum = 0;
                }
                sum = sum + count;
                hm.put(j, sum);
            }
        }
        int chk = 0;
        Collection<Integer> valcol = hm.values();
        casper:
        while (chk < valcol.size()) {
            for (int max : valcol) {
                total = max + total;
                if (total > input5) {
                    al = new ArrayList(hm.keySet());
                    Object obj = al.get(chk);
                    rep = (Integer) obj;
                    break casper;
                }
                chk++;
            }
        }
        return rep;
    }
}

【问题讨论】:

    标签: java hashmap


    【解决方案1】:

    您的 java 编译器版本低于1.7&lt;&gt; 仅允许在 1.7+ 中使用。 更改项目属性并使其使用1.7+ 编译或将代码更改为:

    static HashMap&lt;Integer, Integer&gt; hm = new HashMap&lt;Integer,Integer&gt;();

    注意:如何检查编译器版本。

    1. Right click on the project.
    2. properties.
    3. java compiler
    

    【讨论】:

    • 如何使用低于 1.7 的编译器版本执行此操作?
    • @Alberto - 低于 1.7 的版本无法执行此操作。
    【解决方案2】:

    如果您使用的是 java 1.6 或更低版本,则必须提及泛型类型。仅 java 1.7 及更高版本支持 因此,要支持您可以使用的任何版本

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

    【讨论】:

      【解决方案3】:

      改成HashMap hm = new HashMap&lt;Integer, Integer&gt;();

      【讨论】:

      • hm 声明类型实际上应该是 HashMap&lt;Integer, Integer&gt;
      猜你喜欢
      • 2014-12-17
      • 1970-01-01
      • 2011-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      • 2020-01-31
      相关资源
      最近更新 更多