0

I am trying to deep copy list of objects from a global arraylist and return all the objects in my return function as below

ArrayList<Objects> list = new ArrayList<Objects>();

public Objects copy() {
        Objects copied = new Objects();
        ArrayList<Objects > newList = new ArrayList<Objects>();
        for(Objects  objs : list){
            newList.add(objs);
        }
        for(int i=0; i<newList.size(); i++ ){
            copied = newList.get(i);
        }
        return copied;
    }

But this function only returns the very last element in the list. How do I make the function return all values? For eg if there are 3 objects in the global list my function should return all the 3 values.

Also I do not want my function return type to be an ArrayList<Objects> ie I dont want to return an ArrayList of Objects

Is this possible? If so what am I missing?

4
  • 1
    You want to return all 3 values, but you don't want to return an ArrayList<Objects>? If you return Objects it will only be one element. So what do you want to return? Commented Feb 22, 2014 at 2:23
  • A method can only return one thing. What's the reason you don't want to return a list? BTW here you are doing a shallow copy. A deep copy creates new objects. Commented Feb 22, 2014 at 2:28
  • You simply return the last because you iterate over the entire list and always store the current item in copied. Commented Feb 22, 2014 at 2:34
  • That's not making a "deep copy". All it is is a very expensive way to retrieve the last element of the source list. Commented Feb 22, 2014 at 2:37

1 Answer 1

1

Why not just use the Apache Commons Lang SerializationUtils clone()?

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.