57 容器(十一)——Collections容器工具类

Collections是一个工具类,它提供了与集合操作有关的方法,好比数组中的Arrays工具类。(jdk中的工具类名都是xxxs,有关工具类名参考:https://zhuanlan.zhihu.com/p/93737066

工具类一般不提供构造方法,直接使用类名点的方式调用方法。

只能对List类使用

常用的几个方法有

  • sort()方法:排序
  • reverse()方法:逆序排序
  • shuffle()方法:随机排序
  • binarySearch()方法:折半查找
  • fill()方法:用某个对象替换全部元素
package _20191213;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Collections是一个工具类,它提供了与集合操作有关的方法
 * 好比数组中的Arrays工具类
 * 工具类都是直接使用,不向外提供构造方法,如:Math.xxx()
 * @author TEDU
 *
 */
public class CollectionsTest {
	public static void main(String[] args) {
		LinkedList<String> ml = new LinkedList<>();
		ml.add("suck");
		ml.add("my");
		ml.add("ass");
		Collections.sort(ml);//排序
		System.out.println("排序");
		Iterator<String> it = ml.iterator();
		while(it.hasNext()) {
			System.out.println(it.next());
		}
		//折半查找
		System.out.println(Collections.binarySearch(ml, "ass"));
		//逆序排序
		System.out.println("逆序排序");
		Collections.reverse(ml);
		Iterator<String> it1 = ml.iterator();
		while(it1.hasNext()) {
			System.out.println(it1.next());
		}
		//随机排序
		System.out.println("随机排序");
		Collections.shuffle(ml);
		Iterator<String> it2 = ml.iterator();
		while(it2.hasNext()) {
			System.out.println(it2.next());
		}
		//填充
		System.out.println("填充fill方法");
		Collections.fill(ml, "sleep");
		Iterator<String> it3 = ml.iterator();
		while(it3.hasNext()) {
			System.out.println(it3.next());
		}
	}
}

  

  

原文地址:https://www.cnblogs.com/Scorpicat/p/12034084.html