当前位置: 首页 > news >正文

Collections工具类(java)

文章目录

  • 7.1 常用方法

参考操作数组的工具类:Arrays,Collections 是一个操作 Set、List 和 Map 等集合的工具类。

7.1 常用方法

Collections 中提供了一系列静态的方法对集合元素进行排序、查询和修改等操作,还提供了对集合对象设置不可变、对集合对象实现同步控制等方法(均为static方法):

排序操作:

  • reverse(List):反转 List 中元素的顺序
  • shuffle(List):对 List 集合元素进行随机排序
  • sort(List):根据元素的自然顺序对指定 List 集合元素按升序排序
  • sort(List,Comparator):根据指定的 Comparator 产生的顺序对 List 集合元素进行排序
  • swap(List,int, int):将指定 list 集合中的 i 处元素和 j 处元素进行交换

查找

  • Object max(Collection):根据元素的自然顺序,返回给定集合中的最大元素
  • Object max(Collection,Comparator):根据 Comparator 指定的顺序,返回给定集合中的最大元素
  • Object min(Collection):根据元素的自然顺序,返回给定集合中的最小元素
  • Object min(Collection,Comparator):根据 Comparator 指定的顺序,返回给定集合中的最小元素
  • int binarySearch(List list,T key)在List集合中查找某个元素的下标,但是List的元素必须是T或T的子类对象,而且必须是可比较大小的,即支持自然排序的。而且集合也事先必须是有序的,否则结果不确定。
  • int binarySearch(List list,T key,Comparator c)在List集合中查找某个元素的下标,但是List的元素必须是T或T的子类对象,而且集合也事先必须是按照c比较器规则进行排序过的,否则结果不确定。
  • int frequency(Collection c,Object o):返回指定集合中指定元素的出现次数

复制、替换

  • void copy(List dest,List src):将src中的内容复制到dest中
  • boolean replaceAll(List list,Object oldVal,Object newVal):使用新值替换 List 对象的所有旧值
  • 提供了多个unmodifiableXxx()方法,该方法返回指定 Xxx的不可修改的视图。

添加

  • boolean addAll(Collection c,T... elements)将所有指定元素添加到指定 collection 中。

同步

  • Collections 类中提供了多个 synchronizedXxx() 方法,该方法可使将指定集合包装成线程同步的集合,从而可以解决多线程并发访问集合时的线程安全问题:
    在这里插入图片描述

import org.junit.Test;
import java.text.Collator;
import java.util.*;public class TestCollections {@Testpublic void test01(){/*public static <T> boolean addAll(Collection<? super T> c,T... elements)将所有指定元素添加到指定 collection 中。Collection的集合的元素类型必须>=T类型*/Collection<Object> coll = new ArrayList<>();Collections.addAll(coll, "hello","java"); // 调用方法添加Collections.addAll(coll, 1,2,3,4);System.out.println(coll);Collection<String> coll2 = new ArrayList<>();Collections.addAll(coll2, "hello","java");//Collections.addAll(coll2, 1,2,3,4);//String和Integer之间没有父子类关系,这个要报错 类型错误}@Testpublic void test02(){/** public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)* 在coll集合中找出最大的元素,集合中的对象必须是T或T的子类对象,而且支持自然排序**  public static <T> T max(Collection<? extends T> coll,Comparator<? super T> comp)*  在coll集合中找出最大的元素,集合中的对象必须是T或T的子类对象,按照比较器comp找出最大者**/List<Man> list = new ArrayList<>();list.add(new Man("张三",23));list.add(new Man("李四",24));list.add(new Man("王五",25));/** Man max = Collections.max(list);//要求Man实现Comparable接口,或者父类实现* System.out.println(max);*/Man max = Collections.max(list, new Comparator<Man>() {@Overridepublic int compare(Man o1, Man o2) {return o2.getAge()-o2.getAge();}});System.out.println(max);}@Testpublic void test03(){/** public static void reverse(List<?> list)* 反转指定列表List中元素的顺序。*/List<String> list = new ArrayList<>();Collections.addAll(list,"hello","java","world");System.out.println(list); // [hello, java, world]Collections.reverse(list);System.out.println(list); // [world, java, hello]}@Testpublic void test04(){/** public static void shuffle(List<?> list)* List 集合元素进行随机排序,类似洗牌,打乱顺序*/List<String> list = new ArrayList<>();Collections.addAll(list,"hello","java","world");Collections.shuffle(list); // 随机ArrayListSystem.out.println(list);}@Testpublic void test05() {/** public static <T extends Comparable<? super T>> void sort(List<T> list)* 根据元素的自然顺序对指定 List 集合元素按升序排序** public static <T> void sort(List<T> list,Comparator<? super T> c)* 根据指定的 Comparator 产生的顺序对 List 集合元素进行排序*/List<Man> list = new ArrayList<>();list.add(new Man("张三",23));list.add(new Man("李四",24));list.add(new Man("王五",25));Collections.sort(list); // 这个要在ManSystem.out.println(list);// 自己定义排序Collections.sort(list, new Comparator<Man>() {@Overridepublic int compare(Man o1, Man o2) {return Collator.getInstance(Locale.CHINA).compare(o1.getName(),o2.getName());}});System.out.println(list);}@Testpublic void test06(){/** public static void swap(List<?> list,int i,int j)* 将指定 list 集合中的 i 处元素和 j 处元素进行交换*/List<String> list = new ArrayList<>();Collections.addAll(list,"hello","java","world");Collections.swap(list,0,2);System.out.println(list);}@Testpublic void test07(){/** public static int frequency(Collection<?> c,Object o)* 返回指定集合中指定元素的出现次数*/List<String> list = new ArrayList<>();Collections.addAll(list,"hello","java","world","hello","hello");int count = Collections.frequency(list, "hello");System.out.println("count = " + count);}@Testpublic void test08(){/** public static <T> void copy(List<? super T> dest,List<? extends T> src)* 将src中的内容复制到dest中*/List<Integer> list = new ArrayList<>();for(int i=1; i<=5; i++){//1-5list.add(i);}List<Integer> list2 = new ArrayList<>();for(int i=11; i<=13; i++){//11-13list2.add(i);}Collections.copy(list, list2);System.out.println(list);List<Integer> list3 = new ArrayList<>();for(int i=11; i<=20; i++){//11-20list3.add(i);}//java.lang.IndexOutOfBoundsException: Source does not fit in dest//Collections.copy(list, list3);//System.out.println(list);// copy 方法必须前面的数组size()必须比后面的大 /test 10 有描述}@Testpublic void test09(){/** public static <T> boolean replaceAll(List<T> list,T oldVal,T newVal)* 使用新值替换 List 对象的所有旧值*/List<String> list = new ArrayList<>();Collections.addAll(list,"hello","java","world","hello","hello");Collections.replaceAll(list, "hello","song");System.out.println(list);}@Testpublic void test10(){List src = Arrays.asList(45, 43, 65, 6, 43, 2, 32, 45, 56, 34, 23);//void copy(List dest,List src):将src中的内容复制到dest中//错误的写法:
//        List dest = new ArrayList();//正确的写法:List dest = Arrays.asList(new Object[src.size()]);Collections.copy(dest,src);System.out.println(dest);}@Testpublic void test11(){//提供了多个unmodifiableXxx()方法,该方法返回指定 Xxx的不可修改的视图。List list1 = new ArrayList();//list1可以写入数据list1.add(34);list1.add(12);list1.add(45);List list2 = Collections.unmodifiableList(list1);//此时的list2只能读,不能写list2.add("AA");//不能写System.out.println(list2.get(0));//34}@Testpublic void test12(){//Collections 类中提供了多个 synchronizedXxx() 方法List list1 = new ArrayList();//返回的list2就是线程安全的List list2 = Collections.synchronizedList(list1);list2.add(123);HashMap map1 = new HashMap();//返回的map2就是线程安全的Map map2 = Collections.synchronizedMap(map1);}
}class  Man implements Comparable {private String name;private int age;public Man(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Man{" +"name='" + name + '\'' +", age=" + age +'}';}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Man man = (Man) o;return age == man.age && Objects.equals(name, man.name);}@Overridepublic int hashCode() {return Objects.hash(name, age);}@Overridepublic int compareTo(Object o) {if(this == o){return 0;}if(o instanceof Man){Man man =(Man) o;int value = this.age - man.age;if(value != 0){return value;}return - this.name.compareTo(man.name);}throw new RuntimeException("输入的类型不匹配!");}
}
http://www.lryc.cn/news/106733.html

相关文章:

  • C++ 第六弹 STL
  • 蓝桥杯上岸每日N题 第四期(最少刷题数)!!!
  • STM32 LWIP UDP 一对一 一对多发送
  • 【有趣的设计模式】23 种设计模式详解和场景分析
  • 【数据结构与算法】TypeScript 实现图结构
  • 《golang设计模式》第一部分·创建型模式-04-抽象工厂模式(Abstract Factory)
  • 改进粒子群算法优化BP神经网络---回归+分类两种案例
  • VSCode和QT联合开发
  • YOLO5-1 使用YOLO5检测 水面漂浮物记录
  • MongoDB教程-7
  • Redisson提供优秀的并发控制机制
  • Linux: 设置qmake的Qt版本
  • 使用LLM插件从命令行访问Llama 2
  • gateway过滤器没生效,特殊原因
  • 长相思追剧小游戏
  • leetcode做题笔记51
  • Windows同时安装两个版本的JDK并随时切换,以JDK6和JDK8为例,并解决相关存在的问题(亲测有效)
  • 【ChatGPT辅助学Rust | 基础系列 | Cargo工具】Cargo介绍及使用
  • 全面了解CPU Profiler:解读CPU性能分析工具的核心功能与用法
  • rust format!如何转义{},输出{}?
  • 真人AI写真的制作方法-文生图换脸
  • vscode如何包含第三方库
  • 【Docker】Docker安装Consul
  • 《吐血整理》进阶系列教程-拿捏Fiddler抓包教程(20)-Fiddler精选插件扩展安装让你的Fiddler开挂到你怀疑人生
  • 计算机top命令
  • DevExpress WPF Tree List组件,让数据可视化程度更高!(二)
  • lc1074.元素和为目标值的子矩阵数量
  • elementUi el-radio神奇的:label与label不能设置默认值
  • git仓库清理
  • 从0到1开发go-tcp框架【3-读写协程分离、引入消息队列、进入连接管理器、引入连接属性】【基础篇完结】