[英]How do I insert values into a Map<K, V>?
I am trying to create a map of strings to strings. 我正在尝试创建字符串到字符串的映射。 Below is what I've tried but neither method works.
以下是我尝试过但两种方法都不行。 What's wrong with it?
它出什么问题了?
public class Data
{
private final Map<String, String> data = new HashMap<>();
data["John"] = "Taxi Driver";
data.put("John", "Taxi Driver");
}
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. 方括号仅适用于Java中的数组,因此只能与整数索引一起使用。
data.put
is correct but that is a statement and so must exist in a method block. data.put
是正确的,但这是一个语句,因此必须存在于方法块中。 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: 如果要将地图初始化为类的静态字段,则可以使用
Map.of
,因为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: 在Java 9之前,您可以使用静态初始化程序块来完成同样的事情:
public class Data {
private static final Map<String, String> DATA = new HashMap<>();
static {
DATA.put("John", "Taxi Driver");
}
}
The two errors you have in your code are very different. 您的代码中的两个错误是非常不同的。
The first problem is that you're initializing and populating your Map
in the body of the class without a statement. 第一个问题是你在没有语句的情况下在类的主体中初始化和填充
Map
。 You can either have a static Map
and a static {//TODO manipulate Map}
statement in the body of the class, or initialize and populate the Map in a method or in the class' constructor. 您可以在类的主体中使用静态
Map
和static {//TODO manipulate Map}
语句,也可以在方法或类的构造函数中初始化和填充Map。
The second problem is that you cannot treat a Map
syntactically like an array
, so the statement data["John"] = "Taxi Driver";
第二个问题是你不能在语法上将
Map
视为array
,因此语句data["John"] = "Taxi Driver";
should be replaced by data.put("John", "Taxi Driver")
. 应该由
data.put("John", "Taxi Driver")
代替。 If you already have a "John" key in your HashMap
, its value will be replaced with "Taxi Driver". 如果您的
HashMap
已有“John”键,则其值将替换为“Taxi Driver”。
语法是
data.put("John","Taxi driver");
Try this code 试试这个代码
HashMap<String, String> map = new HashMap<String, String>();
map.put("EmpID", EmpID);
map.put("UnChecked", "1");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.