1

I am wondering how I could produce a clone of my array in the following scenario:

private List<TestObject> testList = Collections.synchronizedList(new ArrayList<TestObject>());

....

public synchronized List<TestObject> getAllTestObjects(){
    return testList.clone();
    //I have tried casting to List<TestObject>
}

It is moaning about clone() being undefined for List. But I am not sure how best to get around it?

Any help would be greatly appreciated.

2 Answers 2

3

You need to use the constructor provided by ArrayList

public synchronized List<TestObject> getAllTestObjects(){
    return new ArrayList<TestObject>(testList);        
}
Sign up to request clarification or add additional context in comments.

4 Comments

is the synchronized required here?
Yes because the copy constructor runs a loop over the given list. See my related answer here - that's for a Set but the same logic holds.
Ist it safe to just synchronize the method execution when copying the list? AFAIK, you should synchronize on the testList itself.
@erdal.karaca that depends entirely on your program logic and is a topic too broad for a comment.
0

This should work:

private static class TestObject {
}
private TestObject[] objects = new TestObject[10];
private List<TestObject> testList = 
  Collections.synchronizedList(new ArrayList<TestObject>(Arrays.asList(objects)));

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.