首页 > 代码库 > Collecions对于集合类的操作

Collecions对于集合类的操作

 

一、排序操作

package CollectionTest;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class CollectionListTest {

	public static void main(String[] args) {
		List L1=new LinkedList();
		L1.add(5);
		L1.add(51);
		L1.add(50);
		L1.add(48);
		L1.add(59);
		
		Collections.shuffle(L1);
		System.out.println(L1);
        Collections.reverse(L1);
        System.out.println(L1);
        Collections.sort(L1);
        System.out.println(L1);
        Collections.swap(L1, 2, 3);
        System.out.println(L1);
//        [59, 48, 51, 5, 50]
//        [50, 5, 51, 48, 59]
//        [5, 48, 50, 51, 59]
//        [5, 48, 51, 50, 59]


	}

}

 

二、查找、替换

package CollectionTest;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SearchTest {

	public static void main(String[] args) {
	List nums=new ArrayList();
	 nums.add(2);
	 nums.add(3);
	 nums.add(0);
	 nums.add(13);
	 nums.add(10);
	 System.out.println(nums);
	 
	 System.out.println(Collections.binarySearch(nums,0));
	 System.out.println(Collections.max(nums));
	 System.out.println(Collections.min(nums));
	     Collections.fill(nums, 8);
	     System.out.println(nums);
	     System.out.println(Collections.frequency(nums, 8));
	 
	 Collections.replaceAll(nums, 8, 2);
	 System.out.println(nums);
		

	}

}

 

三、同步控制

package CollectionTest;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

public class SynchorinedTest {
	public static void main(String[] args)
		{
		Collection c1=Collections.synchronizedCollection(new ArrayList());
		List l1=Collections.synchronizedList(new ArrayList());
		Set  s1=Collections.synchronizedSortedSet(new TreeSet());
		Map  m1=Collections.synchronizedMap(new HashMap());
		
		
		}
	

}

 

四、设值不可变集合

package CollectionTest;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class UnmodifiableTEST {
	public static void main(String[] args)
	{
		//创建一个空的emptyList()
		List l1=Collections.emptyList();
		l1.add(5);
		l1.add(51);
		System.out.println(l1);
		//UnsupportedOperationException  不支持修改异常
		Set s1=Collections.singleton("tianjianke");
		
		Map socres=new HashMap();
		socres.put("1",1);
		Map m1=Collections.unmodifiableMap(socres);
		
		
		
	}

}

  

技术分享

Collecions对于集合类的操作