企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] # 集合 ## 集合继承关系图 ![](https://box.kancloud.cn/ff3304c09ec8e6bee72ebf9e835f9bd7_732x350.png) ![](https://img.kancloud.cn/ad/4d/ad4d657ea66480eaeaffa5f4acd7ec79_1033x507.png) list叫链,set叫集 list允许存储重复的,set不允许存储重复的 ## 基本方法 ~~~ public boolean isEmpty(): 判断当前集合是否为空 ~~~ ![](https://box.kancloud.cn/6dd774e3a008658cbb6ecc52d70672eb_870x351.png) 创建集合的方式 ~~~ 方式一: Collection<元素类型> 变量名=new ArrayList<元素类型>(); 方式二: Collection 变量名=new ArrayList(): ~~~ ## ArrayList和LinkedList的区别 1. ArrayList是实现了基于动态数组的数据结构,而LinkedList是基于链表的数据结构; 2. 对于随机访问get和set,ArrayList要优于LinkedList,因为LinkedList要移动指针; 3. 对于添加和删除操作add和remove,一般大家都会说LinkedList要比ArrayList快,因为ArrayList要移动数据。但是实际情况并非这样,对于添加或删除,LinkedList和ArrayList并不能明确说明谁快谁慢 ## 长度的3种表现形式 数组.length 属性 返回int 字符串.length() 方法,返回值int 集合.size() 方法,返回值int # 迭代器 **集合中把这种取元素的方式描述在Iterator接口中** ## 常用方法 ![](https://box.kancloud.cn/4b769bbef477859254423f91e2706e47_895x198.png) ~~~ //for循环迭代写法: for (Iterator<String> it2 = coll.iterator(); it2.hasNext(); ) { System.out.println(it2.next()); } //存储时提升了Object。取出时要使用元素的特有内容,必须向下转型。 Collection coll = new ArrayList(); coll.add("abc"); coll.add("aabbcc"); coll.add("shitcast"); Iterator it = coll.iterator(); while (it.hasNext()) { //由于元素被存放进集合后全部被提升为Object类型 //当需要使用子类对象特有方法时,需要向下转型 String str = (String) it.next(); System.out.println(str.length()); } ~~~ # 增强for循环 JDK1.5新特性,增强for循环 JDK1.5版本后,出现新的接口java.lang.Iterable Collection是继承Iterable Iterable作用,实现增强for循环 **弊端:没有索引,不能操作容器里面的元素** ## 格式 ~~~ for (数据类型 变量名 : 数组或集合) { } ~~~ ~~~ int[] arr={1,2,3,4,5}; for(int i : arr) { System.out.println(i); } ~~~ # Collections线程安全 java提供的容器类Collection、List、Map、Set、SortedMap、SortedSet都是非线程安全的,当多线程访问这些容器类时,可能会出现数据同步导致的问题,java的工具类java.util.Collections提供了将非同步对象转换为同步对象的方法,如下: ~~~         Collections.synchronizedCollection( c);         Collections.synchronizedList(list)         Collections.synchronizedMap(m)         Collections.synchronizedSet(s)         Collections.synchronizedSortedMap(m)         Collections.synchronizedSortedSet(s) ~~~ 这些方法的作用就是在原有容器的类的方法内部实现逻辑中加入了同步关键字syschronized.