在映射中插入值<K,V>[英] Inserting values in Map< K, V >

本文是小编为大家收集整理的关于在映射中插入值<K,V>的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我正在编写我的第一个应用程序,我正在尝试创建一个可以存储一些信息的地图.

我正在使用 ECLIPSE,但我一直收到同样的错误,但我已经用 Google 搜索(实际上是 DuckDuckGo-ed)并在 StackOverflow 中搜索,但我找不到错误......所以我拼命来到这里.

库已正确导入(因为 ADT 会这样做),我猜 Oracle 文档没问题,所以... 为什么它不起作用?

我的意思是,这两种方法都不能将键值对插入映射中.

在此处输入图片描述

有趣的部分来自于查看错误.

第一个说Syntax error on token ",", { expected after this token
第二个说 Syntax error, insert "}" to complete ClassBody

我开始有点绝望了,我无法让代码更简单!非常感谢!

推荐答案

这里有两个问题.首先你必须把它放到一个方法中,其次你不能使用 [] 语法;你必须使用 Map.put.

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

本文地址:https://www.itbaoku.cn/post/978757.html

问题描述

I'm programming my first app, and I am trying to create a Map that will store some information.

I'm using ECLIPSE and I keep getting the same error, but I have Googled (actually DuckDuckGo-ed) and search in StackOverflow and I can't find the error... So I've desperately come here.

Libraries are imported correctly (since the ADT does so) and I'm guessing Oracle documentation is okay, so... why isn't it working?

I mean, neither of both methods work to insert a Key-Value pair into the map.

enter image description here

The interesting part comes when looking at the errors.

The first one says Syntax error on token ",", { expected after this token
The second says Syntax error, insert "}" to complete ClassBody

I am beginning to get a bit desperate, I couldn't make the code simpler! Thank you very much!

推荐答案

There are two issues here. First you must put this into a method, and second, you can't use the [] syntax; you must use Map.put.

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