of方法
List接口,Set接口,Map接口:里边增加了一个静态的方法of,可以给集合一次性添加多个元素 static <E> List<E> of(E... elements)
使用前提:当集合中存储的元素的个数已经确定了,不在改变时使用
注意:
1.of方法只适用于List接口,Set接口,Map接口, 不适用于接接口的实现类
2.of方法的返回值是一个不能改变的集合, 集合不能再使用add,put等操作方法,会抛出异常 不允许操作异常
3.Set 接口和 Map接口在调用of方法的时候,不能有重复的元素,否则会抛出异常 Map是key不能重复
List<String> list = List.of("a", "b", "a", "c", "d"); 可以重复
Set<String> set = Set.of("a", "b", "c", "d"); 不能重复
Map<String, Integer> map = Map.of("张三", 18, "李四", 19, "王五", 20); (key,value)
不能再使用add remove put等操作的方法
Collection 与Map
添加方法 :
Collection使用add Map 使用put
添加多个所有Collection可用 Collections.addAll( )
循环方法
Collection
1. 普通for循环 使用get()索引方法 2.用集合生成迭代器 用while 循环 3.用增强for循环
Map
1.使用KeySet取出key 放入set集合 用增强for循环 2.使用KeySet取出key 放入set集合用集合生成迭代器 用while 循环
索引
有索引 Collection 下的 List 下的 ArrayList LinkedList 集合
无索引 Collection 下的 Set 下的 HashSet LinkedHashSet 集合 Map所有集合
无序的: HashSet HashMap
重复 带有Set表示不重复的 自定义类型时,必须重写 Hascode 和 equals 方法
排序 1.类实现Comparable<>泛型接口 重写 compareTo() 方法
2.匿名内部类 Collections.sort(intan, new Comparator<Integer>() { });