Java新字段getter为null

时间:2018-03-26 10:37:00

标签: java syntax nullpointerexception hashmap attributes

我在地图中存储绑定到某人的个性化物品:

public class Steven {
    private HashMap<String, Object> myItems = new HashMap<>();

    public Object getMyItem(String key){
        Object i = myItems.get(key);
        if (i == null){
            myItems.put(key, new Integer(0));
            return getMyItem(key);
        }
        return i;
    }
}

所以外部使用:

public static void main(String[] args){
    Steven steve = new Steven();
    int age = steve.getMyItem("age");
    System.out.printLn("steven's age is " + age + ", ");

    int[] eyeColors = steve.getMyItem("eye_colors");
    System.out.printLn("and his left eye's color idx is " + eyeColors[0] + ", and right eye's color idx is " + eyeColors[1]);
}

显然eyeColors会导致语法失败。那么我可以添加到getMyItem方法的任何额外检查,以便当我想要int []时,如果存储的项为null,它将返回int []。

如果是这样,请以任何不会导致我需要在方法中添加额外输入的方式。即我不想要这样的东西:

public Object getMyItem(String key, Object ifNullThenThisNewInstance)

编辑:是否有任何通用对象我可以返回:

int[] o = steve.getMyItem("thing1");

int o1 = steve.getMyItem("thing2");

会起作用吗?

1 个答案:

答案 0 :(得分:0)

我认为解决方案是修改您的方法签名,以便至少可以理解您想要的输出类型。 例如

int age = steve.getMyItem("age",1,"int"); // Being obvious that age for a person would be one number, second field here represents the data type your want your answer in

    int[] eyeColors = steve.getMyItem("eye_colors", 2,"int");//Again being obvious that a person has two eyes
//For example if you need String also
String hairColor = steve.getMytem("hair_color",1,"String");

以下内容可以是Steven类的代码

public class Steven {
            private HashMap<String, Object> myItems = new HashMap<>();

            public Object getMyItem(String key, int size, String datatype){
                Object i = myItems.get(key);
                if (i == null){
                    switch(datatype){
                     case "int":
                           int[] output = new int[size];
                           for(int j=0; j<size;j++){
                               output[j] = someSource.get(j); // Assuming you have some array with these numbers stored
                           }
                           myItems.put(key, output);
                          return size ==1 ? ((int[])output)[0]: output ;

                     case "String":
                     default:
                           String[] out = new String[size];
                           for(int j=0; j<size;j++){
                               out[j] = someSource.get(j); // Assuming you have some array with these numbers stored
                           }
                           myItems.put(key, out);
                          return size ==1 ? ((String[])out)[0]: out ;
                    }
                }
             return i;   
            }

    }