threads
List copy example
This is an example of how to make a safe List copy. Making a safe List copy implies that you should:
- Create a new synchronized ArrayList, using the
synchronizedList(List list)
API method of Collections. - Add elements to the list, using
add(Object e)
API method of List. - Create a new array from the list, using
toArray(T[] a)
API method of List. - An other way is to put the list in a
synchronized
statement and again put the list elements in a new array. - Print all elements of the array, using the
output(String[] word)
method of the example.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class SafeListCopy extends Object { public static void output(String[] word) { System.out.println("characters=" + word.length); for (int i = 0; i < word.length; i++) { System.out.println("word[" + i + "]=" + word[i]); } } public static void main(String[] args) { List wordList = Collections.synchronizedList(new ArrayList()); wordList.add("JavaCodeGeeks"); wordList.add("is"); wordList.add("cool!"); String[] aword = (String[]) wordList.toArray(new String[0]); output(aword); String[] bword; synchronized (wordList) { int size = wordList.size(); bword = new String[size]; wordList.toArray(bword); } output(bword); String[] cword; synchronized (wordList) { cword = (String[]) wordList.toArray(new String[wordList.size()]); } output(cword); } }
Output:
characters=3
word[0]=JavaCodeGeeks
word[1]=is
word[2]=cool!
characters=3
word[0]=JavaCodeGeeks
word[1]=is
word[2]=cool!
characters=3
word[0]=JavaCodeGeeks
word[1]=is
word[2]=cool!
This was an example of how to make a safe List copy in Java.