java 出现“无法解析放置符号”错误时如何将键和值添加到 Hashmap
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34158839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add keys and values to a Hashmap while getting 'cannot resolve put symbol' error
提问by Aziz S. Kural
I am working with Android Studio 1.4.1 and I had just created a Hashmap and was following a tutorial (on java) on how to populate and manipulate it. However I get a 'cannot resolve symbol put' error and the "put" command is in red. The image I added shows the auto complete snapshot and although java.util.HashMap is imported there is no "put" command that is available in autocomplete. The available commands also are showing in red. I tried to use them instead of the "put" command. I keep having this type of problem all along. Can anyone help? Thank you in advance...
我正在使用 Android Studio 1.4.1,我刚刚创建了一个 Hashmap,并且正在学习有关如何填充和操作它的教程(关于 Java)。但是,我收到“无法解析符号放置”错误并且“放置”命令为红色。我添加的图像显示了自动完成快照,尽管导入了 java.util.HashMap,但在自动完成中没有可用的“放置”命令。可用命令也显示为红色。我尝试使用它们而不是“放置”命令。我一直有这种类型的问题。任何人都可以帮忙吗?先感谢您...
import java.util.HashMap;
HashMap<String, String> pozisyon = new HashMap<String, String>();
pozisyon.put("SKale", "a8");
回答by Lubo Kanev
EDIT: You cannot add elements in HashMap fields outside of methods. Things like this wont work:
编辑:您不能在方法之外的 HashMap 字段中添加元素。这样的事情是行不通的:
public class Class {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("one", "two");
}
If you want to achieve that, put it in the constructors, like so:
如果您想实现这一点,请将其放入构造函数中,如下所示:
public class Class {
HashMap<String, String> hashMap = new HashMap<String, String>();
public Class() {
hashMap.put("one", "two");
}
}
Other way you can do it is in a static
block.
您可以使用的其他方法是在static
块中。
回答by Arman Hakim Sagar
try this:
试试这个:
public class Class {
HashMap arrayList1 = new HashMap<>();;
arrayList1.put("32","Bangalore");
arrayList1.put("32","India");
}