集合
Collection集合
集合的概念
ArrayList就是一个集合,集合是Java提供的一种容器,可以用来存储多个数据
集合与数组的区别
1.数组的长度是固定的,集合的长度是可变的
2.数组中存储的是同一类型的元素,可以存储基本数据类型。集合中存储的是对象,且对象的类型可以不一致,在开发中,一般当对象多的时候,使用集合进行存储。
集合框架的介绍
集合的常用功能
Collection<String> collection = new HashSet<>(); //多态
Collection<String> collection = new ArrayList<>();
collection.add("liu");//哪种实现类都可以用
iterator接口的介绍
【注意】iterator是个接口,在collection中的iterator() 方法会返回iterator的实现类,iterator是Collection接口的方法,是所有集合所共有的方法。
迭代器iterator的代码实现
//多态 接口 实现类对象
//用接口去接收实现类对象
Iterator<String> it = coll.iterator();
迭代器的实现原理
增强for循环
【注意】collection接口继承了iterable接口,实现这个接口(iterable)允许对象成为 “foreach” 语句的目标,数组也可以用增强for循环。
泛型
泛型的概念
使用泛型的好处
定义和使用泛型的类
【注意】E只是一个符号,当然也可以取其他的符号,<>中只能是引用类型,不支持基本数据类型。
含有泛型的方法
含有泛型的接口
含有泛型的接口有两种使用方式
泛型通配符
泛型的通配符:
?:代表任意的数据类型
使用方法:
不能创建对象使用
ArrayList<?> list = new ArrayList<?>(); //报错的
只能作为方法的参数使用
泛型的上限限定:<? extends E>代表使用的泛型只能是E类型的子类/本身
泛型的下限限定:<? super E>代表使用的泛型只能说E类型的父类/本身
数据结构
栈:先进后出
队列:先进先出
数组:查询快,增删慢。【注意】个人觉得数组的增删有问题
链表:【注意】表中单链表和双链表的理解有问题
树:
树/二叉树/排序树(查找树)/平衡树/红黑树
List集合
List这个接口就是有序的
介绍
arraylist:List接口的大小可变数组的实现。底层当add,会调用System.arraycopy新建数组。线程不安全(此实现不同步)
linkedlist线程不安全(此实现不同步)
【注意】:pop和push都是对第一个链表元素进行操作
Vector可增长的对象数组。是同步的(线程安全的)。
Set
hashset
哈希值
【注意】p1==p2说明比较的是真实地址
System.out.println("重地".hashCode()); //1179395
System.out.println("通话".hashCode()); //1179395
System.out.println("重地"=="通话"); // false
System.out.println("重地".equals("通话")); // false
哈希表
set集合不允许重复的原理
hashset存储自定义类型元素
【注意】==比较的是地址。equals比较的也是地址,若重写的话,可不同。
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age &&
Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
linkedhashset的有序性
可变参数
Collections
Collections工具类的方法
comparable接口和comparator接口的不同见上图。
map集合
map常用子类
map常用方法
【注意】
int v1 = map.remove(key);//自动拆箱 NullPointerException
Integet v2 = map.remove(key);//没问题
map集合遍历
【注意】hashmap的键和值都可以为null。
entry键值对对象
HashMap<String, String> map = new HashMap<>();
String put = map.put("liu", "1");
String put1 = map.put("chun", "2");
String put2 = map.put("lei", "3");
Set<Map.Entry<String, String>> entries = map.entrySet();
Iterator<Map.Entry<String, String>> iterator = entries.iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> next = iterator.next();
System.out.println(next.getKey() + " "+next.getValue());
}
System.out.println(map);
for (Map.Entry<String, String> entry : entries) {
}
hashmap存自定义类型
linkedhashmap
hashtable
【注意】key和value都不能为null;线程安全。
jdk9的新特性:对添加元素的优化
debug的使用