简体   繁体   English

在java中使用HashMap创建对象

[英]Object creation with HashMap in java

I am trying to create object of a class as a value of HashMap in java. 我试图在java中创建一个类的对象作为HashMap的值。 Below is my java code : 下面是我的java代码:

public interface Message {
    public String nextMessage(String data);
} 

public class DataMessage implements Message{
    private static String[] randomData;

    public DataMessage(String data) {
        randomData = data.split(",");
    }

    @Override
    public String nextMessage(String data) {
        int index = randomIndex.nextInt(randomData.length-1);
        return randomData[index];
    }
}

When I access that object it is returning null ie throwing null pointer exception. 当我访问该对象时,它返回null,即抛出空指针异常。

I am trying to access that object as below : 我试图访问该对象如下:

public class MyMessage {

    public MyMessage() {
    }

    public static void main() {
        HashMap<String,Message> hash = new HashMap<String,Message>();
        if (some condition) {
            hash.put(key,new DataMessage("this is my data"));
        }

        <some code>

        hash.get(key).nextMessage();
        //Throws nullpointer exception
    }
}

Can anyone please help me to understand why this is happening? 谁能帮助我理解为什么会这样?

I am beginner in java and trying to improve performance of this approach. 我是java的初学者,并试图提高这种方法的性能。 Please suggest better approaches if any. 请提出更好的方法。

I think you can't access to you if(){} so your HashMap is always empty for that you get NullPointException because when you try to use hash.get(key).nextMessage(); 我认为你无法访问if(){}所以你的HashMap总是空的,因为你得到NullPointException因为当你尝试使用hash.get(key).nextMessage(); the first part hash.get(key) is null so you can't make null.nextMessage(); 第一部分hash.get(key)为null所以你不能使null.nextMessage();

so to solve your problem make sure that your HashMap is not empty and there are an element with this key. 所以要解决你的问题,请确保你的HashMap不是空的,并且有一个带有这个键的元素。

if (hash .containsKey(key)) {
    //key exists
    hash.get(key).nextMessage();
} else {
    //key does not exists
    System.out.println("No key exist");
}

Note I think you have some error in your function for example this method should return some thing or a void : 注意我认为你的函数有一些错误,例如这个方法应该返回一些东西或一个void

public RandomData(String data) {
     randomData = data.split(",");
}

Hope this can help you. 希望这可以帮到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM