集合
如何保存多个数据?
数组:
- 长度必须指定,一旦指定不能更改。
- 保存的必须为同一类型的元素。(
泛型?
) - 使用数组进行增加/删除元素的示意代码——比较麻烦。
集合:
- 可以
动态保存
任意多个对象,使用比较方便。 - 提供了一些列方便的操作对象的方法:add、remove、set、get等。
- 使用集合添加删除元素的示意代码——简洁。
单列集合:
双列集合:
什么是集合
概念
对象的容器,实现了对对象常用的操作
和数组的区别
- 数组长度固定,集合长度不固定
- 数组可以存储基本类型和引用类型,集合只能存储引用类型
位置
java.util.*;
Collection体系
Collection 父接口
特点:代表一组任意类型的对象,无序、无下标、不能重复。
创建集合 Collection collection = new ArrayList();
常用方法
-
添加
// 添加一个对象
boolean collection.add(Object obj);
// 将一个集合中所有对象添加到此集合中
boolean collection.addAll(Collection c);
-
删除元素
// 在此集合中移出obj对象
boolean collection.remove(Object obj);
// 清空此集合中的所有对象
void collection.clear();
// 移出此collection中那些也包含在指定collection中的所有元素
boolean collection.removeAll(Collection<?> c);
// 仅保留此collection中那些也包含在指定collection中的所有元素
bollean collection.retainAll(Collection<?> c);
-
遍历元素(重点)
-
使用增强for(因为无下标)
for(Object object : collection){ }
-
使用迭代器
//haNext(); 有没有下一个元素 //next(); 获取下一个元素 //remove(); 删除当前元素 Iterator it = collection.iterator(); while(it.hasNext()){ String object = (String)it.next(); //强转 // 可以使用it.remove(); 只能用迭代器的方法移除元素 // collection.remove(); 不能用collection其他方法 会报并发修改异常 }
-
集合转数组
Object[] collection.toArray();
-
-
判断
// 检查此集合中是否包含obj对象
boolean collection.contains(Object obj);
// 判断此集合是否为空
boolean collection.isEmpty();
// 比较此集合是否与指定对象相等
boolean equals(Object obj);
List 子接口
特点:有序、有下标、元素可重复
创建集合对象 List list = new ArrayList<>( );
常用方法
-
添加元素
list.add();
会对基本类型进行自动装箱 -
删除元素 可以用索引
list.remove(0)
当删除数字与索引矛盾时 对数字强转
list.remove((Object) 10)
或list.remove(new Integer(10))
-
遍历
-
使用for遍历
for(int i = 0; i < lise.size(); i++){ sout(list.get(i)); }
-
使用增强for
for(Object list: collection){ }
-
使用迭代器
Iterator it = collection.iterator(); while(it.hasNext()){ String object = (String)it.next(); //强转 // 可以使用it.remove(); 进行移除元素 // collection.remove(); 不能用collection其他方法 会报并发修改异常 }
-
使用列表迭代器 💡(注意和迭代器区别)
ListIterator li = list.listIterator(); while(li.hasNext()){ System.out.println(li.nextIndex() + ":" + li.next()); //从前往后遍历 } while(li.hasPrevious()){ System.out.println(li.previousIndex() + ":" + li.previous()); //从后往前遍历 }
-
-
获取
list.indexOf( );
-
返回子集合
sublist(x, y);
左闭右开List subList = list.subList(1, 3);
返回索引 1、2的值集合
List实现类
- ArrayList 【重点】
- 数组结构实现,必须要连续空间,查询快、增删慢
- jdk1.2版本,运行效率块、线程不安全
- Vector
- 数组结构实现,查询快、增删慢
- jdk1.0版本,运行速度慢、线程安全
- LinkedList
- 双向链表结构实现,无需连续空间,增删快,查询慢
ArrayList
数组结构实现,查询快、增删慢;JDK1.2版本,运行效率快、线程不安全
创建集合 List arrayList = new ArrayList<>();
-
添加元素
arrayList.add();
-
删除元素
arrayList.remove(new Student("name", 10));
正常new对象传参是移出不掉的,这里重写了 equals(this == obj) 方法
public boolean equals(Object obj){ //1 判断是不是同一个对象 if(this == obj){ return true; } //2 判断是否为空 if(obj == null){ return false; } //3 判断是否是Student类型 if(obj instanceof Student){ Student == (Student)obj; //4 比较属性 if(this.name.equals(s.getName()) && this.age == s.getAge()){ return true; } } //5 不满足条件返回false return false; }
-
遍历元素【重点】
-
使用迭代器
Iterator it = arrayList.iterator(); while(it.hasNext()){ Student s = (Student)it.next(); //强转 }
-
列表迭代器
ListIterator li = arrayList.listIterator(); while(li.hasNext()){ Student s = (Student)li.next(); //从前往后遍历 } while(li.hasPrevious()){ Student s = (Student)li.previous();//从后往前遍历 }
-
-
判断
arrayList.contains();
和arrayList.isEmpty();
-
查找(根据下标查找)
arrayList.indexof();
原码分析
private static final int DEFAULT_CAPACITY = 10; //默认容量为10
注意:如果没有向集合中添加任何元素时List list = new ArrayList();
,容量0;添加一个元素后,容量为10;之后添加元素每次扩容1.5倍。
// private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!! 增长修改个数
elementData[size++] = e;
return true;
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
//每次扩容是原来的1.5倍
transient Object[] elementData;存放元素的数组
private int size; 实际元素个数
Vector
数组结构实现,查询快、增删慢;JDK1.0版本,运行效率慢、线程安全
创建集合 Vector vector = new Vector<>();
增加、删除、判断同上
遍历中枚举器遍历
Enumeration en = vector.elements();
while(en.hasMoreElements()){
String o = (String)en.nextElement();
sout(o);
}
LinkedList
双向链表结构实现,增删快,查询慢。
创建链表集合LinkedList li = new LinkedList<>();
常用方法与List一致(迭代器同样支持listIterator()
)
原码分析
类中有三个属性
// size
transient int size = 0;
// 指向第一个元素
transient Node<E> first;
// 指向最后一个元素
transient Node<E> last;
add()
方法
public boolean add(E e) {
linkLast(e);
return true;
}
/**
* 下面代码说白了就是添加元素时,
* 让原本的last变成prev,
* 让当前的传入元素变为item
*/
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
ArrayList和LinkedList对比
泛型
-
jdk1.5引入的新特性,本质是参数化类型,把类型作为参数传递
-
常见形式有泛型类、泛型接口、泛型方法
-
语法:
常见的T、E、K、V称为类型占位符
,表示一种引用类型,可以写多个逗号隔开(尖括号包裹) -
好处:
- 提高代码重用性
- 防止类型转换异常,提高代码安全性
-
注意:
泛型只能使用引用类型
不同泛型类类型对象之间不能相互赋值
泛型类
public class Demo6<T, E> {
// 使用泛型T
// 1. 创建变量
T t;
E e;
/**
* T虽然是类型,但不能直接拿来new对象,
* 因为不确定该对象类型,
* 起码不能保证其构造方法不是私有的
*/
// T t2 = new T();
// 2. 泛型方法(可做参数或返回值)
public void setT(T t){
this.t = t;
}
public T getT(){
return this.t;
}
}
class TestDemo6{
public static void main(String[] args) {
Demo6<String, Object> demo6 = new Demo6<>();
demo6.t = "hello";
System.out.println(demo6.getT());
demo6.setT("hey");
System.out.println(demo6.getT());
}
}
泛型接口
语法:接口名
注意:不能声明泛型静态常量(常量需要实例化,T为包装类又不能直接拿来new对象)
public class Demo7 {
public static void main(String[] args) {
Demo7InterfaceImpl1 demo7InterfaceImpl1 = new Demo7InterfaceImpl1();
demo7InterfaceImpl1.server("八嘎");
Demo7InterfaceImpl2<Integer> demo7InterfaceImpl2 = new Demo7InterfaceImpl2<>();
demo7InterfaceImpl2.server(2000);
}
}
interface Demo7Interface<T> {
String NAME = "张三";
T server(T t);
}
/**
* 方式一:
* 实现接口时直接传入泛型类型
*/
class Demo7InterfaceImpl1 implements Demo7Interface<String> {
@Override
public String server(String s) {
System.out.println(s);
return s;
}
}
/**
* 方式二:
* 实现接口时对实现类传入泛型,
* 将传入的泛型作为接口的泛型类型,
* 实现类的泛型应与接口泛型保持一致
*/
class Demo7InterfaceImpl2<T> implements Demo7Interface<T>{
@Override
public T server(T t) {
System.out.println(t);
return t;
}
}
泛型方法
语法:在方法返回值类型前加泛型——<T, E> void
方法中的泛型作用域只在当前方法中,它可以作为参数、返回值类型,也可用于方法当中——public <T> T test(T t){return t;}
public class Demo8 {
public static void main(String[] args) {
Demo8 demo8 = new Demo8();
demo8.show("熊熊");
demo8.show(58946);
}
// 泛型方法
public <T> void show(T t){
System.out.println(t);
}
}
泛型集合
概念:参数化类型、类型安全的集合,强制集合元素的类型必须一致
特点:
- 编译时即可检查,而非运行时抛出异常
- 访问时,不必类型转换(拆箱)
- 不同泛型之间应用不能相互赋值,
泛型不存在多态
声明集合不注明泛型时默认为Object类型,即:
List list= new ArrayList();
等价于
List<Object> list= new ArrayList<>();
Set子接口
特点:无序、无下标、元素不可重复
方法:全部继承自Collection接口中的方法
增、删、遍历、判断与collection一致
public class Demo1 {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("苹果");
set.add("小米");
set.add("中兴");
System.out.println(set.size()); // 3
System.out.println(set); // [苹果, 中兴, 小米]
set.add("中兴");
System.out.println(set.size()); // 3
System.out.println(set); // [苹果, 中兴, 小米]
System.out.println("---------增强for--------");
for (String s : set) {
System.out.println(s);
}
System.out.println("----------迭代器----------");
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
// 判断元素是否存在
System.out.println(set.contains("小米"));
// 集合判空
System.out.println(set.isEmpty());
}
}
HashSet 【重点】
存储结构:哈希表(数组+链表+红黑树)
存储过程(重复依据):
-
根据HashCode计算元素保存的位置,如果位置为空,直接保存,若不为空,进行第二步
-
再执行equals方法,如果equals为true,则认为是重复,否则形成链表
特点
- 基于HashCode计算元素存放位置
- 基于equals方法判断是否和已有的重复
- 对于以上两种方法可以根据需求进行重写
TreeSet
特点
-
基于排列顺序实现元素不重复
-
存储结构:红黑树
-
实现SortedSet接口,
对集合元素自动排序
public class Demo4 { public static void main(String[] args) { TreeSet<String> treeSet = new TreeSet<>(); treeSet.add("cc"); treeSet.add("ca"); treeSet.add("ff"); treeSet.add("fa"); treeSet.add("ee"); treeSet.add("ea"); treeSet.add("bb"); treeSet.add("ba"); treeSet.add("dd"); treeSet.add("da"); System.out.println(treeSet.size()); // [ba, bb, ca, cc, da, dd, ea, ee, fa, ff] // 根据字母序号排序 System.out.println(treeSet.toString()); } }
Comparable接口
元素对象的类型必须实现Comparable接口
,指定排序规则。(实现Comparable接口必要重写compareTo方法,等于说为该类型对象定义一个排序规则。)
class Person implements Comparable<Person> {
private String name;
private int age;
/**
* 此处略去有参无参构造
* 略去get、set方法
* 略去toString方法
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null){
return false;
}
if (o instanceof Person){
Person p = (Person)o;
return this.name.equals(p.getName()) && this.age == p.getAge();
}
return false;
}
@Override
public int hashCode() {
return this.name.hashCode() + this.age;
}
@Override
public int compareTo(Person o) {
// 先按姓名比,再按年龄比
int n1 = this.getName().compareTo(o.getName());
int n2 = this.getAge() - o.getAge();
return n1==0?n2:n1;
}
}
treeSet集合中通过compareTo方法确定是否为重复元素,而非equals方法
Comparator接口
Comparator接口
同样可以确定添加元素是否已经存在,此时元素对象的类就无须实现Comparable接口了,只不过Comparator接口是在定义TreeSet时实现的。
public class Demo6 {
public static void main(String[] args) {
// 创建集合并指定比较规则
TreeSet<Person> persons = new TreeSet<>(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
// 先比较年龄再比较姓名
int n1 = o1.getAge() - o2.getAge();
int n2 = o1.getName().compareTo(o2.getName());
return n1==0?n2:n1;
}
});
Person p1 = new Person("窦鹏森", 20);
Person p2 = new Person("小熊", 20);
Person p3 = new Person("千层", 6);
Person p4 = new Person("闺女", 6);
persons.add(p1);
persons.add(p2);
persons.add(p3);
persons.add(p4);
persons.add(new Person("闺女", 6));
System.out.println(persons.toString());
}
}
SortedSet接口
Map接口
Map接口的特点
- 用于存储任意键值对(key - value)
- 键:无序、无下标、
不允许重复(唯一)
- 值:无序、无下标、允许重复
方法:
1. V put(K key, V value) 将对象存到集合中,关联键值。key重复则覆盖原值
2. Object get(Object key) 根据键获得对应的值
3. Set<K> 返回所有的Key
4. Collection<V> values() 返回包含所有值的Collection集合
5. Set<Map.Entry<K, V>> 键值匹配的Set集合
Map接口的使用
public class Demo7 {
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("姓名", "Spence_Dou");
map.put("年龄", 20);
map.put("性别", "男");
map.put("身高", 180);
System.out.println(map.toString());
map.remove("身高");
System.out.println(map.toString());
// keySet方法返回的是一个set集合,存放的是所有的key
// Set<String> strings = map.keySet();
for (String key : map.keySet()){
System.out.println(map.get(key));
}
// entrySet方法返回的是一个K:V映射对集合;遍历效率高于keySet
// Set<Map.Entry<String, Object>> entries = map.entrySet();
for (Map.Entry<String, Object> entry : map.entrySet()) {
// 遍历key
System.out.println(entry.getKey());
// 遍历value
System.out.println(entry.getValue());
}
System.out.println(map.containsKey("姓名"));
System.out.println(map.containsValue(20));
}
}
HashMap 【重点】
- jdk1.2版本,线程不安全,运行效率快
- 允许null作为key或value
- 默认初始容量为16,默认加载因子(所占空间超过75%时开辟新空间)为0.75
- 存储结构:哈希表(数组+链表+红黑树)
- 增、删、遍历、判断与上述一致
原码分析总结:
- HashMap刚创建时,table是null,节省空间,当添加第一个元素时,table容量调整为16
- 当元素个数大于阈值(16*0.75 = 12)时,会进行扩容,扩容后的大小为原来的两倍,目的是减少调整元素的个数
- jdk1.8 当每个链表长度 >8 ,并且数组元素个数 ≥64时,会调整成红黑树,目的是提高效率
- jdk1.8 当链表长度 <6 时 调整成链表
- jdk1.8 以前,链表时头插入,jdk1.8之后为尾插入
Hashtable
- jdk1.0版本,线程安全,运行效率慢
- 不允许null作为key或是value
- 初始容量为11,加载因子为0.75
- 存储结构:哈希表
Properties
-
hashtable的子类,要求key和value都是string
-
通常用于配置文件的读取(结合流操作使用)
TreeMap
实现了SortedMap接口(是map的子接口),可以对key自动排序
public class Demo3 {
public static void main(String[] args) {
// 也可在Student类中实现Comparable接口,进而重写compareTo方法(红黑树存储,因此必须排序比较)
Map<Student, String> treeMap = new TreeMap<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getStuNo() - o2.getStuNo();
}
});
Student s1 = new Student("大魔王", 9527);
Student s2 = new Student("蝙蝠侠", 6410);
Student s3 = new Student("卢本伟", 7061);
treeMap.put(s1, "五五开");
treeMap.put(s2, "哥谭");
treeMap.put(s3, "牛逼");
System.out.println(treeMap.size());
System.out.println(treeMap.toString());
}
}
Collection工具类
概念:集合工具类,定义了除了存取以外的集合常用方法
public class Demo1 {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(584);
list.add(586);
list.add(254);
list.add(548);
list.add(658);
list.add(783);
System.out.println(list.toString());
// 升序排序(元素类型必须实现Comparable接口)
Collections.sort(list);
System.out.println(list.toString());
// binarySearch二分查找,返回下标
System.out.println(Collections.binarySearch(list, 73));
List<Integer> copy = new ArrayList<>();
for (int i = 0; i < list.size(); i++){
copy.add(0);
}
// copy数组要求两个数组的size必须相同
Collections.copy(copy, list);
System.out.println(copy.toString());
// reverse反转
Collections.reverse(list);
System.out.println(list.toString());
// shuffle随机打乱集合
Collections.shuffle(list);
System.out.println(list.toString());
// List转数组(定义数组的长度小于list时会自动扩容,大于list时多余元素位为空
Integer[] arr = list.toArray(new Integer[6]);
System.out.println(Arrays.toString(arr));
// 数组转List,此时list受限制,不能改变长度,即不能添加和删除
List<Integer> integers = Arrays.asList(arr);
System.out.println(integers.toString());
// 基本类型数组转换为集合时需要先修改为包装类
int[] nums = {100,200,300,400};
// 否则生成集合元素为基本类型数组
List<int[]> numsList = Arrays.asList(nums);
}
}
补充:
// list转成数组
Integer[] arr = list.toArray(new Integer[10]);
sout(arr.length);
sout(Array.toString(arr));
// 数组转成集合
// 此时为受限集合,不能 添加和删除!
String[] name = {"张三","李四","王五"};
List<String> list2 = Arrays.asList(names);
// 把基本类型数组转为集合时,需要修改为包装类
Integer[] nums = {100, 200, 300, 400, 500};
List<Integer> list3 = Arrays.asList(nums);