2

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?

4
  • return a copy of newAl? Commented May 21, 2013 at 5:08
  • You need to clone the list before sending. Commented May 21, 2013 at 5:08
  • Or after sending, depending on what A actually is. Commented May 21, 2013 at 5:08
  • Thanks for replying .I can manipulate only Test class. Commented May 21, 2013 at 5:16

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.