Java中创建只读容器,同步容器

我们通过Collections.unmodifiableX来得到只读容器,因为容器被设为只读的,所以必须填入有意义的数据之后才进行设置

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collection;

import java.util.Collections;

import java.util.HashSet;

import java.util.List;

import java.util.Set;





/*

 * 创建只读容器

 */

public class Test{

	public static Collection<String> data = new ArrayList<String>(Arrays.asList("AAA BBB CCC DDD".split(" ")));	

	public static void main(String[] args) {

		Collection<String> c = Collections.unmodifiableCollection(data);

		System.out.println(c);

		//c.add("EEE");

		List<String> list = Collections.unmodifiableList(new ArrayList<String>(data));

		System.out.println(list);

		//list.add("EEE");

		

		Set<String> s =  Collections.unmodifiableSet(new HashSet<String>(data));

		System.out.println(s);

		//s.add("EEE");

		/*

		Collections.unmodifiableSortedMap(m);

		Collections.unmodifiableMap(m);

		Collections.unmodifiableSortedMap(m);

		*/

	}



}

  

我们可以通过Collections.synchronizedX来创建线程同步的容器

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collection;

import java.util.Collections;

import java.util.HashSet;

import java.util.List;

import java.util.Set;





/*

 * 创建同步容器

 */

public class Test{

	public static Collection<String> data = new ArrayList<String>(Arrays.asList("AAA BBB CCC DDD".split(" ")));	

	public static void main(String[] args) {

		Collection<String> c = Collections.synchronizedCollection(data);

		List<String> list = Collections.synchronizedList(new ArrayList<String>(data));

		list.add("AAA"); list.add("BB");

		/*

		 * Collections.synchronizedMap(m);

		 * Collections.synchronizedSortedMap(m);

		 * Collections.synchronizedSet(s);

		 * Collections.synchronizedSortedSet(s);

		 */

	}



}

  

 

 

 

你可能感兴趣的:(java)