集合-Collections工具

1.定义

  Collections是集合类的一个工具类,它提供了一系列静态方法用于对容器中的元素进行排序和搜索等一系列操作。

  注:Collection是一个集合接口,而Collections是一个有着操作容器的方法的工具类。

2.方法

(1)reverse(List<?> list) :  使List中的数据发生反转

 1  List<Integer> list = new ArrayList<>();
 2 
 3         for(int i = 0; i<10; i++ ){
 4             list.add(i);
 5         }
 6 
 7         System.out.println("反转前的List中数据顺序:");
 8         System.out.println(list);
 9 
10         //反转操作
11         Collections.reverse(list);
12 
13         System.out.println("反转后的List中的数据顺序:");
14         System.out.println(list);

经过反转后的数据为:

反转前的List中数据顺序:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
反转后的List中的数据顺序:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

(2)  shuffle(List<> list) :         混淆List中的数据顺序  

1 Collections.shuffle(list);

得到的数据为:

混淆前的List中数据顺序:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
混淆后的List中的数据顺序:
[0, 6, 8, 2, 5, 9, 1, 3, 7, 4]

(3)sort(List<> list) :      将List中的数据进行排序,使用sort方法可以根据元素的自然顺序 对指定列表按升序进行排序。列表中的所有元素都必须实现 Comparable 接口。此列表内的所有元素都必须是使用指定比较器可相互比较的。当然,我们也可以选择自己构建比较器,来将列表中的元素自己进行排序——>sort(List<> list,Comparator c)  

1  Collections.sort(list);

我们将上面混淆后的数据再排序后得到的数据:

List中的数据顺序:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
混淆后的List中的数据顺序:
[2, 3, 5, 7, 1, 0, 8, 9, 4, 6]
排序后的List中的数据顺序:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

(4)swap(List<> list, int i, int j)  :   将List中  下标为 i 的数据  与  下标为 j 的数据 进行位置交换

1 Collections.swap(list,1,6);

得到的数据为:

List中的数据顺序:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
交换后的List中的数据顺序:
[0, 6, 2, 3, 4, 5, 1, 7, 8, 9]

(5)rotate(List<> list , int i) : 将List中的数据,向右滚动指定长度单位。如果 i 是负数,则向左滚动。

1 Collections.rotate(list,2);
2 Collections.rotate(list,-2);

得到的数据:

List中的数据顺序:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
向右滚动后的List中的数据顺序:
[8, 9, 0, 1, 2, 3, 4, 5, 6, 7]
向左滚动后的List中的数据顺序:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

(6)fill(List<> list,Object o)  : 将List中的全部数据替换为指定的数据o

Collections.fill(list,8);

结果:

List中的数据顺序:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
替换后的List中的数据顺序:
[8, 8, 8, 8, 8, 8, 8, 8, 8, 8]

(7)copy(List<? extends T> dest , List<? extends T> src )  :  用两个参数,一个目标 List 和一个源 List,  将源List的元素拷贝到目标,并覆盖它的内容。目标 List 至少与源一样长。如果它更长,则在目标 List 中的剩余元素不受影响。

 Collections.copy(dest,src);

结果:

dest中的数据顺序:
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 99, 991]
src中的数据顺序:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
替换后的dest中的数据顺序:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 99, 991]

 Collections还有很多方法,如min,max,还有线程安全方法等,总之Collections是一个用于操作List集合的工具类,有许多实用的功能。

 该文参考了博客:https://www.cnblogs.com/cathyqq/p/5279859.html

猜你喜欢

转载自www.cnblogs.com/wqq-blog/p/10557785.html
今日推荐