Java对象参考 [英] Java Object reference

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

问题描述

这与另一个类实例变量返回的ArrayList的使用有关.

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("");
    }

}

在Test类中,当我检索列表并操作列表时,由于引用,A类列表也被操纵.如果A是第三方代码的一部分.如何在Test类中更正我的代码,以便原始对象会不会受到影响?

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?

推荐答案

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

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

我认为最好这样做,但是根据您的工作,您可能需要在吸气剂中构造新的List.这也有助于隐藏类型.

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.

这篇关于Java对象参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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