Java Object reference

风流意气都作罢 提交于 2019-12-24 03:23:38

问题


This is regarding the usage of ArrayList returned by another class instance variable.

Class A {

    //assigned list of string to it.
    private List < String > newAl;
    //returns the list
    public List < String > getList() {
        return newA1;
    }
}

Class Test {

    public void go() {
        List < String > list = a.getList();
        list.add("");
    }

}

In the Test class when i retreive list and manipulate the list.Because of the reference ,class A list also got manipulated.If A is part of third party code.How do I correct my code in Test class so that original object wouldnt be affected?


回答1:


The ArrayList constructor takes a Collection so you can use that:

List<String> list = new ArrayList(a.getList());

I think it's better to do it like this, but depending on what you're doing, you may want to construct the new List in the getter. That also helps type hiding.



来源:https://stackoverflow.com/questions/16662472/java-object-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!