【问题标题】:Java HashMap content to String [duplicate]Java HashMap内容到字符串[重复]
【发布时间】:2016-02-24 08:10:29
【问题描述】:

降分前请阅读 cmets!

我想将HashMap 的内容转换为String,就像使用Arrays.toString(arrayList)ArrayList 转换为String

有可能吗? 有简单的方法吗?

我是否必须使用 Iterator 进行迭代和附加?例如:

HashMap<String, ArrayList<MyObject>> objectMap = new HashMap<String, ArrayList<>>();

//.... put many items to objectMap

Iterator it = objectMap.entrySet().iterator();

while(it.hasNext()){
  Map.Entry pairs = (Map.Entry) it.next();
  System.out.println(pairs.getKey() + " = " + pairs.getValue());
}

我认为这是不同的,因为对 &lt;String, ArrayList&gt; 而不是 &lt;String, Integer&gt;

【问题讨论】:

    标签: java hashmap


    【解决方案1】:

    您可以使用toString()Map

    String content = objectMap.toString();
    

    Map 覆盖了toString() 方法,因此可以轻松获取map 的内容。

    我应该举个例子:

    public static void main(String[] args) throws Exception {
        HashMap<String, List<MyObject>> objectMap = new HashMap<>();
        List<MyObject> list = new ArrayList<>();
        list.add(new MyObject(12, 12));
        objectMap.put("aaaa", list);
        String content = objectMap.toString();
        System.out.println("content = " + content);
    }
    
    private static class MyObject {
        int min;
        int max;
    
        public MyObject(int max, int min) {
            this.max = max;
            this.min = min;
        }
    
        @Override
        public String toString() {
            return "MyObject{" +
                    "max=" + max +
                    ", min=" + min +
                    '}';
        }
    }
    

    这是输出:

    content = {aaaa=[MyObject{max=12, min=12}]}
    

    所以这意味着它运作良好

    【讨论】:

    • 不,它不起作用。
    • 不工作的原因是什么?
    • 它返回错误的String,不是内容,而是奇怪的String 关于它来自哪里的包。
    • 这就是原因:public final String toString() { return key + "=" + value; }。如果 value 是一个对象,它的toString() 不会被调用
    • 不,这个问题不属于Serializable
    猜你喜欢
    • 2018-01-02
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    • 2020-05-23
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多