如何在出现“无法解析放置符号"错误时向

How to add keys and values to a Hashmap while getting #39;cannot resolve put symbol#39; error(如何在出现“无法解析放置符号错误时向 Hashmap 添加键和值)

本文介绍了如何在出现“无法解析放置符号"错误时向 Hashmap 添加键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Android Studio 1.4.1,我刚刚创建了一个 Hashmap,并且正在学习如何填充和操作它的教程(关于 java).但是,我收到无法解析符号放置"错误,并且放置"命令为红色.我添加的图像显示了自动完成快照,尽管导入了 java.util.HashMap,但自动完成中没有可用的put"命令.可用的命令也以红色显示.我尝试使用它们而不是put"命令.我一直有这种类型的问题.任何人都可以帮忙吗?提前谢谢你...

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...

import java.util.HashMap;

HashMap<String, String> pozisyon = new HashMap<String, String>();
pozisyon.put("SKale", "a8");

推荐答案

您不能在方法之外的 HashMap 字段中添加元素.这样的事情是行不通的:

You cannot add elements in HashMap fields outside of methods. Things like this wont work:

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

您可以使用 static 块来执行此操作.

Other way you can do it is in a static block.

这篇关于如何在出现“无法解析放置符号"错误时向 Hashmap 添加键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在出现“无法解析放置符号"错误时向

基础教程推荐