修改原始列表对象的问题? [英] Issue in modifying the objects of original list?

查看:24
本文介绍了修改原始列表对象的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了在更改原始列表内容时临时列表也被修改的问题.预期结果应为使用原创".

I have faced problem temporary list is also modified while original list content is being changed. Expected result should be 'Employ Original'.

public static void main(String[] args) {

        List<Employ> e = new ArrayList<Employ>();
        e.add(new Employ("Employ Original"));
        //
        List<Employ> exList = new ArrayList<>(e);
        e.get(0).name = "Employ Modified";

        // Result should be 'Employ Original' 
        System.out.println("" + exList.get(0).name);
    }

    public static class Employ {
        public String name;

        public Employ(String str) {
            this.name = str;
        }
    }

推荐答案

如果需要副本,则需要克隆原始对象.ArrayList 只是为新列表创建新指针.指针仍然只指向原始对象.

You need to clone the original objects if you want copies. The ArrayList is only making new pointers for new lists. The pointers still only point to the original objects.

这篇关于修改原始列表对象的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆