0
点赞
收藏
分享

微信扫一扫

【Java集合】集合选型规则、Collections工具类、Comparable和Comparator的区别

秀儿2020 2022-04-14 阅读 44

一、集合选型规则

根据业务分析:
① 先判断存储对象的类型(一组对象或一组键值对)

② 一组对象:Conllection接口

允许重复:List

不允许重复:Set

③ 一组键值对:Map接口

二、Collections工具类

java.utils.Collections是集合工具类,用来对集合进行操作。

常用方法

reverse(List<?> list) :反转集合中元素的顺序。
shuffle(List<?> list):打乱集合顺序。

sort(List<T> list):将集合中元素按照默认规则排序。
sort(List<T> list,Comparator<? super T>):将集合中元素按照指定规则排序。

swap(List<?> list, int i, int j) :交换集合中指定位置的元素。

max(Collection<? extends T> coll) :根据其元素的自然顺序返回给定集合的最大元素。
max(Collection<? extends T> coll, Comparator<? super T> comp) :根据指定的比较器引发的顺序返回给定集合的最大元素。

min(Collection<? extends T> coll) :根据其元素的自然顺序返回给定集合的最小元素。
min(Collection<? extends T> coll, Comparator<? super T> comp) :根据指定的比较器引发的顺序返回给定集合的最小元素。

frequency(Collection<?> c, Object o) :返回集合中元素出现的次数。

copy(List<? super T> dest, List<? extends T> src) :将所有元素从一个列表复制到另一个列表中。

replaceAll(List<T> list, T oldVal, T newVal) :将列表中一个指定值的所有出现替换为另一个。

addAll(Collection<T> c, T... elements):往集合中添加一些元素。

三、Comparable和Comparator的区别:

Comparable:强行对实现它的每个类的对象进行整体排序。

Comparator:强行对某个对象进行整体排序。

如果在使用的时候,想要独立的定义规则去使用 可以采用Collections.sort(List list,Comparetor<T> c)方式,自己定义规则:

Collections.sort(list, new Comparator<Student>() {
   @Override
   public int compare(Student o1, Student o2) {
       return o2.getAge()-o1.getAge();//以学生的年龄降序
  }
});

如果想要规则更多一些,可以参考下面代码:

Collections.sort(list, new Comparator<Student>() {
           @Override
           public int compare(Student o1, Student o2) {
               // 年龄降序
               int result = o2.getAge()-o1.getAge();//年龄降序
               if(result==0){//第一个规则判断完了 下一个规则 姓名的首字母 升序
                   result = o1.getName().charAt(0)-o2.getName().charAt(0);
              }
               return result;
          }
      });
举报

相关推荐

0 条评论