Java中的集合类——集合元素的排序:工具类Collections的静态方法sort()

版权声明:转载注明来源。Keep Learning and Coding. https://blog.csdn.net/a771581211/article/details/88395395
package day04;

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

/**
 * 集合元素的排序
 * 排序集合使用的是集合的工具类Collections的静态方法sort。
 * 排序仅能对List集合进行,因为Set部分实现类是无序的。
 * @author kaixu
 *
 */
public class SortListDemo {
	
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>();
		
		Random random = new Random();
		
		for(int i=0;i<10;i++){
			list.add(random.nextInt(100)); //输入小于100的随机数
		}
		System.out.println(list); //[42, 48, 30, 39, 86, 42, 91, 28, 61, 10]
		/*
		 * 对集合进行了自然排序(从小到大排序)。
		 */
		Collections.sort(list);  
		/*
		 * Collection是集合的接口,而Collections是集合的工具类
		 * 它提供了许多操作集合的方法。
		 */
		System.out.println(list);  //[10, 28, 30, 39, 42, 42, 48, 61, 86, 91]
	}

}

猜你喜欢

转载自blog.csdn.net/a771581211/article/details/88395395