dcsimg
LinkedIn
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Jun 29, 2021

Using CopyOnWriteArrayList in Java

When you need to add a collection with no duplicates, you can do so using Java's CopyOnWriteArrayList. Using this method avoids duplication as well. The below code snippet shows CopyOnWriteArrayList in action:

*/

import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;

public class CopyOnWriteArrayListEx {
	
	public static void main(String[] args) 
	{  
		CopyOnWriteArrayListEx copyOnWriteArrayListEx = new CopyOnWriteArrayListEx();
		copyOnWriteArrayListEx.proceed();
	}

	private void proceed()  
	{
		Vector firstVector = new Vector();
		firstVector.add("The");
		firstVector.add("world");
		firstVector.add("is");
		
		Vector secondVector = new Vector();
		secondVector.add("is"); //This entry is also present in firstVector
		secondVector.add("beautiful");
		
		CopyOnWriteArrayList copyOnWriteArrayList = new CopyOnWriteArrayList();
		
		copyOnWriteArrayList.addAllAbsent(firstVector);
		copyOnWriteArrayList.addAllAbsent(secondVector);
		
		System.out.println(copyOnWriteArrayList);
	}
}

/*

This code results in the following output:

[root@mypc]# java CopyOnWriteArrayListEx
[The, world, is, beautiful]
Sridhar M S
 
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date