Collentions.sort()方法相关的学习

Collentions.sort()是对泛型的List进行排序的方法,学习中的练习实例,取自慕课网的免费公开学习视频中范例,不断学习补充修正中

package com.collections.demo;


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


/**
 * 将要完成:
 * 1通过Collentions.sort()方法,对Integer泛型的List进行排序;
 * 2对String泛型List进行排序;
 */


public class CollectionsSortDemo {


public static void main(String[] args) {
CollectionsSortDemo csd =new CollectionsSortDemo();
csd.SortDemo1();
System.out.println();
CollectionsSortDemo csd1 =new CollectionsSortDemo();
csd1.SortDemo2();
}
/**1通过Collentions.sort()方法,对Integer泛型的List进行排序;
* 创建一个Integer泛型的List,插入十个100以内的随机数;
* 通过调用Collentins.Sort()方法。对List进行排序;
* 注:对泛型的了解
*/
    public void SortDemo1() {
    List<Integer> integerList=new ArrayList<Integer>();
    Random random =new Random();
    Integer k;
    for (int i=0;i<10;i++) {//10个100以内的随机数
    do {
    k=random.nextInt(100);
    }while(integerList.contains(k));
    integerList.add(k);
    System.out.println("成功添加整数"+k);
    }
    System.out.println("----------排序前-------------");
    for (Integer integer : integerList) {//遍历integerList数组
    System.out.println("元素:"+integer);
}
        //Collections.sort(integerList);//语句位置都可以
        System.out.println("----------排序后------------");
        Collections.sort(integerList);调用Collections.sort()对integerList排序
    for (Integer integer : integerList) {
    System.out.println("元素:"+integer);
}
    }
    /**2通过Collentions.sort()方法,对String泛型的List进行排序;
* 创建一个String泛型的List;
* 通过调用Collentins.Sort()方法。对StringList进行排序;
* 注:对泛型的了解
*/
    public void SortDemo2() {

    List<String> stringList=new ArrayList<String>();//创建String泛型List的对象

        stringList.add("microsoft");

    stringList.add("google");
    stringList.add("lenovo");
    System.out.println("-------排序前-----------");
    for (String string : stringList) {//遍历stringList数组
    System.out.println("元素:"+string);
}
    System.out.println("-------排序后-----------");
       Collections.sort(stringList);//调用Collections.sort()对stringList排序
    for (String string : stringList) {
    System.out.println("元素:"+string);
    }
}

}

输出结果:

成功添加整数2
成功添加整数19
成功添加整数80
成功添加整数34
成功添加整数37
成功添加整数60
成功添加整数90
成功添加整数70
成功添加整数13
成功添加整数24
----------排序前-------------
元素:2
元素:19
元素:80
元素:34
元素:37
元素:60
元素:90
元素:70
元素:13
元素:24
----------排序后------------
元素:2
元素:13
元素:19
元素:24
元素:34
元素:37
元素:60
元素:70
元素:80
元素:90


-------排序前-----------
元素:microsoft
元素:google
元素:lenovo
-------排序后-----------
元素:google
元素:lenovo
元素:microsoft


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值