Home >Java >javaTutorial >How many ways can I synchronize an ArrayList in Java?

How many ways can I synchronize an ArrayList in Java?

WBOY
WBOYforward
2023-08-28 17:41:021011browse

在Java中,有几种方法可以同步一个ArrayList?

ArrayList is a subclass of the AbstractList class, which can be used to store elements of a dynamically sized collection . ArrayList increases its size to accommodate new elements and shrinks in size when elements are removed, hence the name Resizable or dynamic array. ArrayList can allow duplicate values ​​and null values ​​.

There are two methods to synchronize ArrayList in Java

Collections.synchronizedList () method

synchronizedList() method is used to synchronize collections in Java .

Syntax

public static List<T> synchronizedList(List<T> list)

Example

import java.util.*;
public class SynchronizedListTest {
   public static void main(String[] args) {
      List<String> list = new ArrayList<String>();
      list.add("IND");
      list.add("AUS");
      list.add("WI");
      list.add("NZ");
      list.add("ENG");
      List<String> synlist = Collections.<strong>synchronizedList</strong>(list);
      <strong>synchronized</strong>(synlist) {
         Iterator<String> itr = synlist.iterator();
         while(itr.hasNext()) {
            String str = itr.next();
            System.out.println(str);
         }
      }
   }
}

Output

IND
AUS
WI
NZ
ENG

CopyOnWriteArrayList

CopyOnWriteArrayList Will create a list of elements in the specified collection order. It is thread-safe for ArrayList with concurrent access. When an ArrayList is modified, it creates a new copy of the underlying array.

Syntax

public class CopyOnWriteArrayList<E> extends Object implements List<E>, RandomAccess, Cloneable, Serializable

Example

import java.util.*;
import java.util.concurrent.*;
public class CopyOnWriteArrayListTest {
   public static void main(String[] args) {
      <strong>CopyOnWriteArrayList </strong>list = new <strong>CopyOnWriteArrayList</strong>();
      list.add("Java");
      list.add("Scala");
      list.add("Python");
      list.add("Selenium");
      list.add("ServiceNow");
      System.out.println("Displaying synchronized ArrayList: ");
      Iterator itr = list.iterator();
      while(itr.hasNext()) {
         String str = itr.next();
         System.out.println(str);
      }
   }
}

Output

Displaying synchronized ArrayList:
Java
Scala
Python
Selenium
ServiceNow

The above is the detailed content of How many ways can I synchronize an ArrayList in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete