当我的哈希图中的项目被打印出来时,请看以for (Map.Entry<String, World> entry : WorldsByName.entrySet())......开头的代码,只有我添加的最后一个项目会被打印出来。其他人都消失了。
.....
public interface World {
abstract void run(String s);
}
private void sample(String[] inserted) {
Map<String, World> WorldsByName = new HashMap<String, World>();
WorldsByName.put(inserted[1], new World() {
public void run(String s) {
if (inserted[0].equals("house")) {
System.out.println(inserted[0] + " with name " + s + " has been created.");
} else {
System.out.println("What do you mean by " + inserted[0] + " ?");
}
}
});
.....发布于 2015-01-07 12:51:14
您的代码仅在WorldsByName映射中放置单个值
WorldsByName.put(inserted[1], new World() ...因此,当您尝试执行for循环时,它将只针对一个键值执行。
for (Map.Entry<String, World> entry : WorldsByName.entrySet()) {编辑:
对于您的要求,您将需要change the method structure或您将不得不make WorldsByName as global variable。对于您的用例,For循环不是必需的。
对于更改方法结构:
private void sample(String[] inserted, Map<String, World> WorldsByName) {从caller方法传递实例化的WorldsByName,不要在sample方法中初始化(new)它。确保为inserted和WorldsByName在sample方法中添加null检查和all。
为了使WorldsByName成为全局变量:
Map<String, World> WorldsByName = new HashMap<String, World>();
private void sample(String[] inserted) {
// Map<String, World> WorldsByName = new HashMap<String, World>();
WorldsByName.put(inserted[1], new World() {...如果要创建HashMapTest2类的多个实例,则不要将WorldsByName设置为静态,否则也可以将WorldsByName设置为静态
发布于 2015-01-07 12:55:08
您可以尝试一次插入所有项,但值将是对象签名。
static Map<String, World> WorldsByName = new HashMap<String, World>();
private void sample(final String[] inserted) {
for (int i = 0; i < inserted.length; i++)
WorldsByName.put(inserted[i], new World() {
public void run(String s) {
if (inserted[0].equals("house"))
System.out.println(inserted[0] + " with name " + s
+ " has been created.");
else
System.out.println("What do you mean by " + inserted[0]
+ " ?");
}
});
for (Map.Entry<String, World> entry : WorldsByName.entrySet())
System.out.println(entry.getKey() + ":-->" + entry.getValue());
//..your other code here..
}并将该参数设为final,但我不确定您在这里到底要实现什么,除非这将插入一个格式为defparser.HashParser$1@b1c260的键的值
发布于 2015-01-07 13:44:35
我假设,根据您之前的注释,您将只传递两个参数,一个是house/hut/etc.,第二个是name。因此,您使用的是inserted和inserted1。只要您只关心两个参数,这就很好。要保留映射中的值,有多种方法: 1)将HashMap创建为实例变量,并使用相同的对象调用sample方法。例如:
class HashMaptest2{
Map<String, World> worldsByname = new HashMap<String, World>();
etc.
}在main方法中
psvm(){
HashMapTest2 test=new HashMaptest2();
test.sample(inserted1);
test.sample(inserted2)2)第二种方法是在您的主类中创建HashMap,并按照Naman的指示将其传递给sample方法。
https://stackoverflow.com/questions/27812401
复制相似问题