我在尝试使HashMap可以访问其所在类中的其他方法时遇到了麻烦.
这基本上是我想要做的,
class object
method main
this.test=9
method fire
output this.test
Run Code Online (Sandbox Code Playgroud)
这是真正的代码
import java.util.*;
import java.lang.String;
import java.util.HashMap;
public class problem {
public HashMap dict;
public problem() {
HashMap<String, String[]> dict = new HashMap<String, String[]>();
// put everything into hashmap
String[] items = { "toys", "sun" };
dict.put("animal", items);
String[] items_2 = { "fun", "games" };
view.put("human", items_2);
this.view = view;
// start
this.BeginM();
}
public void BeginM() {
System.out.println(this.view.get("human")[0]); // should give "fun"
}
}
Run Code Online (Sandbox Code Playgroud)
我在输出阶段得到这个错误:
array required, but java.lang.Object found
Run Code Online (Sandbox Code Playgroud)
你知道吗?我曾经有过这样的日子,无论你怎么努力,没有什么东西可以完全正常工作,为了让一些工作正常,我将修复你的代码!
我有时会看到人们在这里发布了一些奇怪问题的重写,我总是想知道为什么!? 现在我知道,这是为了弥补你的一个虚拟机无缘无故地喘不过气来的一天,你有一个无法复制的错误,直到你看向别的那一刻,你的狗自发地忘记了他的家庭训练.
无论如何,你需要弄清楚你是否想要调用该变量dict或view.选择一个,但你需要坚持下去.我真的不在乎,但我在dict这里使用.如果您更喜欢另一个,嘿,这是您的代码,做您喜欢的!但是不要同时使用两者,这会让人感到困惑.
你的问题是在你的领域,你只是在使用HashMap.使用花哨的好东西,或演员.否则,HashMap只是持有Objects.一个Object不是一个String[].因此,您需要将结果转换get()为a String[],或者您可以忘记所有这些并使用花哨的良好类型的东西(有时我们称之为"泛型").我将使用花哨的好东西(HashMap<String, String[]>),但就像我说的 - 这是你的代码,如果你想要施放!
无论如何,这让我们:
public class problem
{
HashMap<String, String[]> dict;
public problem()
{
HashMap<String, String[]> dict = new HashMap<String, String[]>();
// put everything into hashmap
String[] items =
{
"toys", "sun"
};
dict.put("animal", items);
String[] items_2 =
{
"fun", "games"
};
dict.put("human", items_2);
this.dict = dict;
// start
this.BeginM();
}
public void BeginM()
{
System.out.println(this.dict.get("human")[0]); // should give "fun"
}
}
Run Code Online (Sandbox Code Playgroud)
看我的第3行?通过将该字段声明dict为a HashMap<String, String[]>,现在BeginM()知道它所拥有的对象类型,您将不再获得该错误.
虽然我会更进一步,使它更简洁,更容易出错:
public class Problem
{
private final HashMap<String, String[]> dict;
public void Problem()
{
dict = new HashMap<String, String[]>();
dict.put("animal", new String[] { "toys, "sun" });
dict.put("human", new String[] { "fun", "games" });
BeginM();
}
public void BeginM()
{
System.out.println(dict.get("human")[0]);
}
}
Run Code Online (Sandbox Code Playgroud)
那我在那里做了什么?好吧,首先我资本化了Problem.让类名以大写字母开头是一种惯例.当然不是强制性的,但它很高兴,尤其是当你与其他开发人员合作时.举个例子:我认为你的构造函数problem是一个缺少返回值的方法!此外,我做了dict最终和私人,这是为了你以后不会意外覆盖该字段.我把它设为私有,这是一个很好的设计.如果其他人需要了解它,我们可以给他们一个访问方法.最后,我摆脱了this.,因为我不喜欢它 - 但是,嘿,仍然是你的代码,如果你想要把它还掉!