Collections tools common method


Complete C language self-study manual (33)

Android multi-resolution framework for adaptation

JavaWeb core technology tutorial series

HTML5 front-end development combat tutorial series

MySQL database gymnastics tutorials (35 graphical version)

And overthrow their own past - Custom View tutorial series (10)

Thinking out of the woods, set foot on the road --Android develop sophisticated Advanced essence record

Android programmers looking to tell the front tutorial series (40 episodes free video tutorials + source code)


Copyright Notice

  • This article original author: Columbia Valley's younger brother
  • On the blog address: http: //blog.csdn.net/lfdfhl

Outline

Collections is a class operation Set Java offers, List and Map and other tools collection. Collections class provides static methods numerous set of operations, the use of these methods can be realized quickly sort the collection of elements, such as search and replace and copy operations

Examples

package com.utils;
import java.util.ArrayList;
import java.util.Collections;
/**
 * 本文作者:谷哥的小弟 
 * 博客地址:http://blog.csdn.net/lfdfhl
 * 
 * Collections工具类使用示例
 */
public class TestCollections {

	public static void main(String[] args) {
		TestCollections testCollections=new TestCollections();
		testCollections.test1();
	}
	
	//添加和排序
	public void test1() {
		ArrayList<String> arrayList=new ArrayList<>();
		arrayList.add("b");
		arrayList.add("c");
		arrayList.add("d");
		arrayList.add("a");
		System.out.println(arrayList);
		//反转集合中的元素
		Collections.reverse(arrayList);
		System.out.println(arrayList);
		//按照自然顺序排序
		Collections.sort(arrayList);
		System.out.println(arrayList);
		//随机排序
		Collections.shuffle(arrayList);
		System.out.println(arrayList);
		//交换集合中的首位元素
		Collections.swap(arrayList, 0, arrayList.size()-1);
		System.out.println(arrayList);
	}
	
	// 查找和替换
	public void test2() {
		ArrayList<Integer> arrayList = new ArrayList<>();
		arrayList.add(9);
		arrayList.add(5);
		arrayList.add(2);
		arrayList.add(7);
		System.out.println(arrayList);
		// 获取集合中的最大值
		Integer max = Collections.max(arrayList);
		System.out.println(max);
		// 获取集合中的最小值
		Integer min = Collections.min(arrayList);
		System.out.println(min);
		// 替换集合中的元素
		Collections.replaceAll(arrayList, 9, 8);
		System.out.println(arrayList);
		// 二分法查找
		Collections.sort(arrayList);
		System.out.println(arrayList);
		int index=Collections.binarySearch(arrayList, 7);
		System.out.println(index);
	}

}

result

Here Insert Picture Description

Released 1022 original articles · won praise 1986 · Views 2.38 million +

Guess you like

Origin blog.csdn.net/lfdfhl/article/details/104547945