There are two issues here.
Firstly, you can't use the []
syntax like you may be able to in other languages. Square brackets only apply to arrays in Java, and so can only be used with integer indexes.
data.put
is correct but that is a statement and so must exist in a method block. Only field declarations can exist at the class level. Here is an example where everything is within the local scope of a method:
public class Data {
public static void main(String[] args) {
Map<String, String> data = new HashMap<String, String>();
data.put("John", "Taxi Driver");
data.put("Mark", "Professional Killer");
}
}
If you want to initialize a map as a static field of a class then you can use Map.of
, since Java 9:
public class Data {
private static final Map<String, String> DATA = Map.of("John", "Taxi Driver");
}
Before Java 9, you can use a static initializer block to accomplish the same thing:
public class Data {
private static final Map<String, String> DATA = new HashMap<>();
static {
DATA.put("John", "Taxi Driver");
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…