HashMap<> error. Illegal start of type

情到浓时终转凉″ 提交于 2019-12-11 03:58:34

问题


Whenever i try to compile this function it gives an error at line 10 --> ErrorMessage : CandidateCode.java.10: illegal start of type static HashMap hm = new HashMap<>(); 1 error I'm trying to compile it on an website's compiler, but when i use netbeans it works completely fine.

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;
    }
}

回答1:


If you are using java version 1.6 or below version you must have mention generic types. Only java 1.7 and upwards support <> Therefore to support any version you can use

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



回答2:


Your java compiler version is less than 1.7. <> are only allowed in 1.7+. Either change the project properties and make it compile with 1.7+ or change the code to :

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

Note : how to check compiler version.

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



回答3:


change it to HashMap hm = new HashMap<Integer, Integer>();



来源:https://stackoverflow.com/questions/25726016/hashmap-error-illegal-start-of-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!