Home > Java > javaTutorial > The Collections tool class provides four static method operations

The Collections tool class provides four static method operations

Y2J
Release: 2017-05-09 11:31:43
Original
3131 people have browsed it

The Collections tool class provides a large number of operations for Collection/Map. This article mainly introduces the Collections tool class_Compiled by the Power Node Java Academy. Friends in need can refer to

The Collections tool class provides a large number of operations for Collection/Map. It can be divided into four categories, all of which are Static (static) method:

1. Sorting operation (mainly related to List interface)

  • ## reverse( List list): Reverse the order of the elements in the specified List collection

  •  shuffle(List list): Randomly sort (shuffle) the elements in the List

  •  sort(List list): Sort the elements in the List according to natural ascending order

  •  sort(List list, Comparator c): Sort with a custom comparator

  •  swap(List list, int i, int j): Swap the element at i and the element out of j in the specified List collection

  •  rotate(List list, int distance): Shift all elements to the right by the specified length. If distance is equal to size, the result remains unchanged

  • public void testSort() {
        System.out.println("原始顺序:" + list);
        Collections.reverse(list);
        System.out.println("reverse后顺序:" + list);
        Collections.shuffle(list);
        System.out.println("shuffle后顺序:" + list);
        Collections.swap(list, 1, 3);
        System.out.println("swap后顺序:" + list);
        Collections.sort(list);
        System.out.println("sort后顺序:" + list);
        Collections.rotate(list, 1);
        System.out.println("rotate后顺序:" + list);
      }
    Copy after login
Output


Original order: [b Zhang San, d Sun Liu, a Li Si, e Qian Qi, c Zhao Wu]

Reverse order: [c Zhao Wu, e Qian Qi, a Li Si, d Sun Liu, b Zhang San]
The order after shuffle: [b Zhang San, c Zhao Wu, d Sun Liu, e Qian Qi, a Li Si]
The order after swap: [b Zhang San, e Qian Qi, d Sun Six, c Zhao Wu, a Li Si]
The order after sorting: [a Li Si, b Zhang San, c Zhao Wu, d Sun Liu, e Qian Qi]
The order after rotating: [e Qian Qi, a Li Si, b Zhang San, c Zhao Wu, d Sun Liu]

2. Search and replace (mainly related to Collection interface)

  •  binarySearch(List list, Object key): Use binary search method to obtain the index of the specified object in the List, provided that the collection has been sorted

  • ## max( Collection coll): Returns the maximum element
  •  max(Collection coll, Comparator comp): Returns the maximum element
  • based on the custom comparator  min(Collection coll): Returns the smallest element
  •  min(Collection coll, Comparator comp): Returns the smallest element
  • based on the custom comparator
  •  fill(List list, Object obj): Fill with the specified object
  •  frequency(Collection Object o): Return the number of times the specified object appears in the specified collection
  •  replaceAll(List list, Object old, Object new): Replace
  •   public void testSearch() {
        System.out.println("给定的list:" + list);
        System.out.println("max:" + Collections.max(list));
        System.out.println("min:" + Collections.min(list));
        System.out.println("frequency:" + Collections.frequency(list, "a李四"));
        Collections.replaceAll(list, "a李四", "aa李四");
        System.out.println("replaceAll之后:" + list);
        
        // 如果binarySearch的对象没有排序的话,搜索结果是不确定的
        System.out.println("binarySearch在sort之前:" + Collections.binarySearch(list, "c赵五"));
        Collections.sort(list);
        // sort之后,结果出来了
        System.out.println("binarySearch在sort之后:" + Collections.binarySearch(list, "c赵五"));
    
        Collections.fill(list, "A");
        System.out.println("fill:" + list);
      }
    Copy after login
  • Output


The given list: [b Zhang San, d Sun Liu, a Li Si, e Qian Qi, c Zhao Wu]

max:e Qian Qi

min:a Li Si
frequency: 1
After replaceAll: [ b Zhang San, d Sun Liu, aa Li Si, e Qian Qi, c Zhao Wu]
binarySearch before sort: -4
binarySearch after sort: 2
fill: [A, A, A , A, A]


3. Synchronization control


Collections tool class provides multiple syn

chr

onizedXxx Method, this method returns the synchronization object corresponding to the specified collection object, thereby solving the security problem of threads when multiple threads concurrently access the collection. HashSet, ArrayList, and HashMap are all thread-unsafe. If synchronization needs to be considered, use these methods. These methods mainly include: synchronizedSet, synchronizedSortedSet, synchronizedList, synchronizedMap, synchronizedSortedMap.
It should be pointed out in particular that when using the iterative method to traverse the collection, you need to manually synchronize the returned collection.

 Map m = Collections.synchronizedMap(new HashMap());
   ...
 Set s = m.keySet(); // Needn't be in synchronized block
   ...
 synchronized (m) { // Synchronizing on m, not s!
   Iterator i = s.iterator(); // Must be in synchronized block
   while (i.hasNext())
     foo(i.next());
 }
Copy after login

4. Set up immutable collections

Collections has three types of methods that can return an immutable collection:

1. emptyXxx(): returns an Empty immutable collection object

2. singletonXxx(): Returns an immutable collection object that only contains the specified object.

3. unmodifiableXxx(): Returns the immutable value of the specified collection object

View

5.

Others1. disjoint(Collection c1, Collection c2) - Returns true if there are no identical elements in the two specified collections.


2. addAll(Collection c, T... a) - A convenient way to add all specified elements to the specified collection. Demonstration:

Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");


3. Comparator reverseOrder(Comparator cmp) - 返回一个比较器,它强行反转指定比较器的顺序。如果指定比较器为 null,则此方法等同于 reverseOrder()(换句话说,它返回一个比较器,该比较器将强行反转实现 Comparable 接口那些对象 collection 上的自然顺序)。

public void testOther() {
    List<String> list1 = new ArrayList<String>();
    List<String> list2 = new ArrayList<String>();
    // addAll增加变长参数
    Collections.addAll(list1, "大家好", "你好","我也好");
    Collections.addAll(list2, "大家好", "a李四","我也好");
    // disjoint检查两个Collection是否的交集
    boolean b1 = Collections.disjoint(list, list1);
    boolean b2 = Collections.disjoint(list, list2);
    System.out.println(b1 + "\t" + b2);
    // 利用reverseOrder倒序
    Collections.sort(list1, Collections.reverseOrder());
    System.out.println(list1);
  }
Copy after login

输出

true false

[我也好, 大家好, 你好]

6. 完整代码

package com.bjpowernode.test;
import java.util.*;
import org.junit.Before;
import org.junit.Test;
public class CollectionsTest {
  private List list = new ArrayList();
  @Before
  public void init() {
    // 准备测试数据
    list.add("b张三");
    list.add("d孙六");
    list.add("a李四");
    list.add("e钱七");
    list.add("c赵五");
  }
  @Test
  public void testUnmodifiable() {
    System.out.println("给定的list:" + list);
    List<String> unmodList = Collections.unmodifiableList(list);
    unmodList.add("再加个试试!"); // 抛出:java.lang.UnsupportedOperationException
    // 这一行不会执行了
    System.out.println("新的unmodList:" + unmodList);
  }
  @Test
  public void testSort() {
    System.out.println("原始顺序:" + list);
    Collections.reverse(list);
    System.out.println("reverse后顺序:" + list);
    Collections.shuffle(list);
    System.out.println("shuffle后顺序:" + list);
    Collections.swap(list, 1, 3);
    System.out.println("swap后顺序:" + list);
    Collections.sort(list);
    System.out.println("sort后顺序:" + list);
    Collections.rotate(list, 1);
    System.out.println("rotate后顺序:" + list);
  }
  @Test
  public void testSearch() {
    System.out.println("给定的list:" + list);
    System.out.println("max:" + Collections.max(list));
    System.out.println("min:" + Collections.min(list));
    System.out.println("frequency:" + Collections.frequency(list, "a李四"));
    Collections.replaceAll(list, "a李四", "aa李四");
    System.out.println("replaceAll之后:" + list);
    // 如果binarySearch的对象没有排序的话,搜索结果是不确定的
    System.out.println("binarySearch在sort之前:" + Collections.binarySearch(list, "c赵五"));
    Collections.sort(list);
    // sort之后,结果出来了
    System.out.println("binarySearch在sort之后:" + Collections.binarySearch(list, "c赵五"));
    Collections.fill(list, "A");
    System.out.println("fill:" + list);
  }
  @Test
  public void testOther() {
    List<String> list1 = new ArrayList<String>();
    List<String> list2 = new ArrayList<String>();
    // addAll增加变长参数
    Collections.addAll(list1, "大家好", "你好","我也好");
    Collections.addAll(list2, "大家好", "a李四","我也好");
    // disjoint检查两个Collection是否的交集
    boolean b1 = Collections.disjoint(list, list1);
    boolean b2 = Collections.disjoint(list, list2);
    System.out.println(b1 + "\t" + b2);
    // 利用reverseOrder倒序
    Collections.sort(list1, Collections.reverseOrder());
    System.out.println(list1);
  }
}
Copy after login

【相关推荐】

1. Java免费视频教程

2. YMP在线手册

3. 全面解析Java注解

The above is the detailed content of The Collections tool class provides four static method operations. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template