开发者

store integer and string in map

I have the following code:

    public Map<String,?> createItem(String title, String caption) {

              Map<String,String> item = new HashMap<String,String>();
                           item.put(ITEM_TITLE, title);
                          item.put(ITEM_CAPTION, caption);
            (***)      item.put(ITEM_NUM, NUM);

in line (*) i have error what i n开发者_Go百科eed to do to add the integer


This would be a bad solution and takes away Generics. Would not recommend this but you can get a clear understanding of how all classes(String,Number) extend the Object class. Prior to Java 5 i.e before Generics, Map was something like Map

public static Map<String, Object> mapTest(String title, String caption) {
        Map<String, Object> item = new HashMap<String, Object>();
        item.put("title", title);
        item.put("caption", caption);
        item.put("count", new Integer(2));
        return item;
    }

When using get(key), a cast will be required.


You cannot add an integer to a Map of strings.


I don't know actually why he needs this, If he wants to create Item then can use oop;i.e better to create class Item{...} and can hold data in it, or if it is something for serialization then simply can go with following: (*) item.put(ITEM_NUM, ""+NUM);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜