Java集合
Collection集合
集合概述
集合、数组都是对多个数据进行存储操作的结构,简称Java容器。内存层面的存储,不涉及持久化存储。
使用Array存储对象方面具有一些弊端,而Java 集合就像一种容器,可以动态地把多个对象的引用放入容器中。
Java 集合类可以用于存储数量不等的多个对象,还可用于保存具有映射关系的 关联数组。
数组在内存存储方面的特点:
- 数组初始化以后,长度就确定了。
- 数组声明的类型,就决定了进行元素初始化时的类型。
数组在存储数据方面的弊端:
- 数组初始化以后,长度就不可变了,不便于扩展。
- 数组中提供的属性和方法有限,不便于进行添加、删除、插入等操作,且效率不高。
- 数组没有现成的属性或方法获取数组中实际元素的个数。
- 初始化一个数组的时候,jvm会在内存上分配一块连续的内存空间,每一个内存空间存一个元素,从首地址开始连续存放,所以数组是有序的,并且存储的数据可以重复的。
Java集合在开发中的应用:
在持久化层通过SQL语句查询到的多条数据映射到Java实体类对象,然后通过集合存储多个实体类对象,返回到业务层。
Java 集合可分为 Collection 和 Map 两种体系:
- Collection接口:单列数据,定义了存取一组对象的方法的集合
- List:元素有序、可重复的集合
- Set:元素无序、不可重复的集合
- Map接口:双列数据,保存具有映射关系“key-value对”的集合
Collection接口继承树:

Map接口继承树:

Collection接口常用方法
Collection 接口是 List、Set 和 Queue 接口的父接口,该接口里定义的方法既可用于操作 Set 集合,也可用于操作 List 和 Queue 集合。
JDK5 之前,Java 集合会丢失容器中所有对象的数据类型,把所有对象都作为 Object 类型处理。从 JDK5增加了泛型以后,Java 集合可以记住容器中对象的数据类型。
Collection接口:单列集合,用来存储一个一个的对象。
collection接口常用方法:
- 添加:
add(Object obj)
:对应基本数据类型或字符串会自动装箱。
addAll(Collection coll)
:将其他集合的元素添加到当前集合。
- 获取有效元素的个数:
int size()
- 清空集合:
void clear()
- 是否是空集合:
boolean isEmpty()
- 是否包含某个元素:
boolean contains(Object obj)
:是通过对象的equals方法来判断是否是同一个对象。
boolean containsAll(Collection coll)
:也是调用对象的equals方法来比较的,拿两个集合的元素挨个比较。
- 删除:
boolean remove(Object obj)
:通过对象的equals方法判断,只会删除找到的第一个元素。
- 取两个集合的差集:
boolean removeAll(Collection coll)
:把差集的结果存在当前集合中。
- 取两个集合的交集:
boolean retainAll(Collection coll)
:把交集的结果存在当前集合中。
- 判断集合是否相等:
boolean equals(Object obj)
- 转成对象数组:
Object[] toArray()
- 获取集合对象的哈希值:
hashCode()
- 遍历:
iterator()
:返回迭代器对象,用于集合遍历。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| public class CollectionTest { @Test public void test(){ Collection coll = new ArrayList(); coll.add("a"); coll.add(123); coll.add(new Date()); int size = coll.size(); System.out.println(size); Collection coll2 = new ArrayList(); coll2.addAll(coll); coll2.clear(); coll2.isEmpty(); boolean contains = coll.contains(new Date()); System.out.println(contains); boolean containsAll = coll.containsAll(coll2); System.out.println(containsAll); coll.remove(123); coll.removeAll(coll2); coll.retainAll(coll2); coll.equals(coll2); int hash = coll.hashCode(); System.out.println(hash); Object[] objects = coll.toArray(); System.out.println(objects); List<String> strings = Arrays.asList(new String[]{"AA", "BB"}); System.out.println(strings); } }
|
Iterator迭代器接口
Iterator对象称为迭代器(设计模式的一种),主要用于遍历 Collection 集合中的元素。
GOF给迭代器模式的定义为:提供一种方法访问一个容器(container)对象中各个元素,而又不需暴露该对象的内部细节。迭代器模式,就是为容器而生。
Collection接口继承了java.lang.Iterable
接口,该接口有一个iterator()
方法,那么所有实现了Collection接口的集合类都有一个iterator()方法,用以返回一个实现了 Iterator接口的对象。
Iterator中的方法:
next()
:游标下移,返回集合中当前游标元素。
hasNext()
:判断集合是否还有下一个元素。
remove()
:移除集合中当前游标元素,可以在遍历的时候删除集合中的元素。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @Test public void test2(){ Collection coll = new ArrayList(); coll.add("a"); coll.add(123); coll.add(new Date()); coll.add(new Person("小明", 19)); Iterator iterator = coll.iterator(); while (iterator.hasNext()){ Object next = iterator.next(); System.out.println(next); if (next.equals("a")){ iterator.remove(); } } }
|
注意:
- 在调用iterator.next()方法之前必须要调用iterator.hasNext()进行检测。若不调用,且下一条记录无效,直接调用iterator.next()会抛出NoSuchElementException异常。
- 集合对象每次调用iterator()方法都得到一个全新的迭代器对象,默认游标都在集合的第一个元素之前。
- 如果还未调用next()或在上一次调用 next 方法之后已经调用了 remove 方法, 再调用remove都会报IllegalStateException
foreach 循环遍历集合元素:
JDK5 提供了 foreach 循环迭代访问 Collection和数组。
遍历集合的底层调用Iterator完成操作。
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class ForTest { @Test public void test(){ Collection coll = new ArrayList(); coll.add("a"); coll.add(123); coll.add(new Date()); coll.add(new Person("小明", 19)); for (Object obj : coll) { System.out.println(obj); } } }
|
注意:
增强for循环不可以对原索引值进行修改,取得的集合或数组的值是以赋值形式传递。
List接口
List接口继承Collection接口,存储有序的、可重复的数据。 类似“动态”数组,替换原的数组。
- List接口实现类异同点:
- ArrayList:作为List接口的主要实现类;线程不安全的,效率高;底层使用
Object[] elementData
存储。
- LinkedList:对于频繁的插入、删除操作,使用此类效率比ArrayList高;底层使用
双向链表
存储。
- Vector:作为List接口的古老实现类;线程安全的,效率低;底层使用
Object[] elementData
存储。
List接口常用方法:
void add(int index, Object obj)
:在index位置插入obj元素。
boolean addAll(int index, Collection coll)
:从index位置开始将coll中的所有元素添加进来。
Object get(int index)
:获取指定index位置的元素。
int indexOf(Object obj)
:返回obj在集合中首次出现的位置,没有则返回-1。
int lastIndexOf(Object obj)
:返回obj在当前集合中末次出现的位置。
Object remove(int index)
:移除指定index位置的元素,并返回此元素。
Object set(int index, Object obj)
:设置指定index位置的元素为obj。
List subList(int fromIndex, int toIndex)
:返回从fromIndex到toIndex位置的子集合,左闭右开原则。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| public class ListTest { @Test public void test(){ List list = new ArrayList<>(); list.add(123); list.add(456); list.add(new Person("小明", 19)); list.add("中国"); list.add(456); list.add(2, 22); System.out.println(list); list.addAll(2, list); System.out.println(list); Object obj = list.get(2); System.out.println(obj); int index = list.indexOf(456); System.out.println(index); int lastIndex = list.lastIndexOf(456); System.out.println(lastIndex); Object reObj = list.remove(5); System.out.println(reObj); list.set(2, "gggg"); System.out.println(list); List<Object> subList = list.subList(5, 8); System.out.println(subList); } }
|
常用方法总结:
- 增:add(Object obj)
- 删:remove(int index) / remove(Object obj)
- 改:set(int index, Object ele)
- 查:get(int index)
- 插:add(int index, Object ele)
- 长度:size()
- 遍历:
- Iterator迭代器方式
- 增强for循环
- 普通的循环
面试题:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class ListExer { @Test public void test(){ List list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); updateList(list); System.out.println(list); } public void updateList(List list){ list.remove(2);
} }
|
ArrayList源码分析
ArrayList 是 List 接口的典型实现类、主要实现类。
JDK8底层源码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; }
public boolean add(E e) { ensureCapacityInternal(size + 1); elementData[size++] = e; return true; }
private void ensureCapacityInternal(int minCapacity) { ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); }
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++; if (minCapacity - elementData.length > 0) grow(minCapacity); }
private void grow(int minCapacity) { int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); elementData = Arrays.copyOf(elementData, newCapacity); }
|
总结:如果此次对ArraList集合添加数据导致底层elementData数组容量不够,则扩容。默认情况下,扩容为原来的容量的1.5倍,同时需要将原有数组中的数据复制到新的数组中。
结论:建议开发中使用带参的构造器:ArrayList list = new ArrayList(int capacity);
LinkedList源码分析
LinkedList源码分析:
- 双向链表,内部没有声明数组,而是定义了Node类型的first和last, 用于记录首末元素。
- 定义内部类Node,作为LinkedList中保存数据的基本结构。Node除了保存数据,还定义了两个变量:
- prev变量记录前一个元素的位置
- next变量记录下一个元素的位置
LikdedList底层源码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| transient Node<E> first;
transient Node<E> last;
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; } }
public boolean add(E e) { linkLast(e); return true; }
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++; }
|
总结:LinkedList底层使用双向链表存储,对于频繁的插入、删除操作,使用此类效率比ArrayList高。
Vector源码分析
JDK1就有了,Vector和ArrayList类似,相对ArrayList底层public方法都加了synchronized关键字。
作为List接口的古老实现类;线程安全的,效率低;底层使用Object[] elementData存储。
Vector底层源码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| public Vector() { this(10); }
public synchronized boolean add(E e) { modCount++; ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = e; return true; }
private void ensureCapacityHelper(int minCapacity) { if (minCapacity - elementData.length > 0) grow(minCapacity); }
private void grow(int minCapacity) { int oldCapacity = elementData.length; int newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); elementData = Arrays.copyOf(elementData, newCapacity); }
|
总结:Vector底层默认初始化长度为10的数组。在扩容方面,默认扩容为原来的数组长度的2倍。
Set接口
Set接口是Collection的子接口,set接口没有提供额外的方法。
Set接口实现类异同点:
- HashSet:作为Set接口的主要实现类;线程不安全的;可以存储null值。
- LinkedHashSet:作为HashSet的子类;遍历其内部数据时,可以按照添加的顺序遍历。
- TreeSet:可以按照添加对象的指定属性,进行排序。
Set集合存储的数据特点:无序的、不可重复的元素。
具体以HashSet为例说明:
- 无序性:不等于随机性。存储的数据在底层数组中并非按照数组索引顺序添加,而是根据添加数据的哈希值决定的。
- 不可重复性:Set 判断两个对象是否相同不是使用
==
运算符,而是根据 equals() 方法,也就是Set集合中添加的元素按照equals()判断时不能返回true。
HashSet分析
HashSet按 Hash算法来存储集合中的元素,因此具有很好的存取、查找、删除性能。
HashSet底层创建和调用的都是HashMap集合的结构,添加的元素为HashMap集合中的key值。
HashSet 具有以下特点:
- 不能保证元素的排列顺序。
- HashSet 不是线程安全的。
- 集合元素可以是 null。
元素添加过程:(以HashSet为例)
调用add()方法向HashSet中添加元素a,首先调用元素a所在类的hashCode()方法,计算元素a的哈希值,此哈希值接着通过某种算法(哈希函数/映射函数)计算出在HashSet底层数组(哈希表)中的存放位置(即为:索引位置),判断数组此位置上是否已经存在元素:
- 如果此位置上没有其他元素,则元素a添加成功。 —>情况1
- 如果此位置上有其他元素b或以链表形式存在的多个元素(链地址法),则比较元素a与其它元素的hash值:
- 如果hash值不相同,则元素a添加成功。**—>情况2**
- 如果hash值相同,进而需要调用元素a所在类的equals()方法:
- equals()返回true,元素a添加失败。
- equals()返回false,则元素a添加成功。**—>情况3**
总结:底层也是数组,初始容量为16,当使用率超过0.75,(16*0.75=12) 且要存放的位置非空时,就会扩大容量为原来的2倍。
对于添加成功的情况2和情况3而言:元素a与已经存在此索引位置上其他数据以链表的方式存储。
JDK 7:元素a放到数组中,指向原来的元素。(头插法)
JDK 8:原来的元素在数组中,指向元素a(尾插法)
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class SetTest { @Test public void test(){ Set set = new HashSet<>(); set.add(123); set.add(456); set.add("AA"); set.add(new User("李四", 19)); set.add(new User("李四", 19)); System.out.println(set); } }
|
User类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| package com.hncj.set;
import java.util.Objects;
public class User { private String name; private int age;
public User(String name, int age) { this.name = name; this.age = age; }
@Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; }
@Override public boolean equals(Object o) { System.out.println("User equals()......"); if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return age == user.age && Objects.equals(name, user.name); }
@Override public int hashCode() { System.out.println("User hashCode()......"); return Objects.hash(name, age); } }
|
执行结果:

总结:对于存放在Set容器中的对象,对应的类一定要重写equals()和hashCode()方法,以实现对象相等规则。即:“相等的对象必须具有相等的散列码”。
LinkedHashSet分析
LinkedHashSet 是 HashSet 的子类。
LinkedHashSet 根据元素的 hashCode 值来决定元素的存储位置, 但它同时使用双向链表维护元素的次序,这使得元素看起来是以插入顺序保存的。当迭代LinkedHashSet集合打印的顺序与插入元素的顺序一致。
LinkedHashSet插入性能略低于 HashSet,但在迭代访问 Set 里的全部元素时有很好的性能。
LinkedHashSet底层结构:

TreeSet分析
TreeSet 是 SortedSet 接口的实现类,TreeSet 可以确保集合元素处于排序状态,向 TreeSet 中添加的应该是同一个类的对象,不然会报java.lang.ClassCastException异常。
TreeSet底层使用红黑树结构存储数据。(类似二叉排序树)
TreeSet 两种排序方法:自然排序和定制排序。默认情况下,TreeSet 采用自然排序。
TreeSet 特点:有序,查询速度比List快。
TreeSet自然排序规则:
如果试图把一个对象添加到 TreeSet 时,则该对象的类必须实现 Comparable
接口。
向 TreeSet 中添加元素时,只有第一个元素无须比较compareTo()方法,后面添加的所有元素都会调用compareTo()方法进行比较。
因为只有相同类的两个实例才会比较大小,所以向 TreeSet 中添加的应该是同一个类的对象。
对于 TreeSet 集合而言,它判断两个对象是否相等的唯一标准是:两个对象通过 compareTo(Object obj)
方法比较返回值,而不再是equals()方法。
1 2 3 4 5 6 7 8 9 10 11 12
| @Test public void test(){ TreeSet<Object> set = new TreeSet<>(); set.add(new User("Jake", 19)); set.add(new User("Mary", 20)); set.add(new User("Fake", 18)); set.add(new User("Tom", 22)); set.add(new User("Jerry", 19)); set.add(new User("Jerry", 11)); System.out.println(set); }
|
User类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public class User implements Comparable<Object>{ private String name; private int age;
public User(String name, int age) { this.name = name; this.age = age; }
@Override public int compareTo(Object o) { System.out.println("User compareTo()......"); if(o instanceof User){ User user = (User)o; int compare = this.name.compareTo(user.name); if (compare != 0){ return compare; }else { return Integer.compare(user.age, this.age); } }else { throw new RuntimeException("类型不匹配!"); } } }
|
TreeSet定制排序规则:
- 通过Comparator接口来实现,需要重写compare(Object o1, Object o2)方法。
- 要实现定制排序,需要将实现Comparator接口的实例作为形参传递给TreeSet的构造器。
- 使用定制排序判断两个元素相等的标准是:通过Comparator比较两个元素返回了0。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| @Test public void test(){ Comparator com = new Comparator(){ @Override public int compare(Object o1, Object o2) { if(o1 instanceof User && o2 instanceof User){ User u1 = (User)o1; User u2 = (User)o2; return Integer.compare(u1.getAge(), u2.getAge()); }else { throw new RuntimeException("类型不匹配!"); } } }; TreeSet<Object> set = new TreeSet<>(com); set.add(new User("Jake", 19)); set.add(new User("Mary", 20)); set.add(new User("Fake", 18)); set.add(new User("Tom", 22)); set.add(new User("Jerry", 19)); set.add(new User("Jerry", 11)); System.out.println(set); }
|
面试题一:打印结果
1 2 3 4 5 6 7 8 9 10 11 12
| HashSet set = new HashSet(); Person p1 = new Person(1001,"AA"); Person p2 = new Person(1002,"BB"); set.add(p1); set.add(p2); p1.name = "CC"; set.remove(p1); System.out.println(set); set.add(new Person(1001,"CC")); System.out.println(set); set.add(new Person(1001,"AA")); System.out.println(set);
|
面试题二:在List内去除重复数字值,要求尽量简单。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public static List duplicateList(List list) { HashSet set = new HashSet(); set.addAll(list); return new ArrayList(set); } public static void main(String[] args) { List list = new ArrayList(); list.add(new Integer(1)); list.add(new Integer(2)); list.add(new Integer(2)); list.add(new Integer(4)); list.add(new Integer(4)); List list2 = duplicateList(list); for (Object integer : list2) { System.out.println(integer); } }
|
Map集合
概述
Map与Collection并列存在。Map用于保存具有映射关系的数据(key-value),通过key能找到对应的 value。
Map中的 key 和 value 都可以是任何引用类型的数据,常用String类作为Map的 key。
Map接口的常用实现类:HashMap、TreeMap、LinkedHashMap和 Properties。其中,HashMap是 Map 接口使用频率最高的实现类。
Map存储结构理解:
- Map 中的 key 是无序的、不可重复的,用Set来存放,即同一个 Map 对象所对应的类,须重写hashCode()和equals()方法。
- Map中的value是无序的、可重复的,使用Collection存储所有的value,value所在的类要重写equals()方法。
- 一个键值对:key-value构成了一个Entry(Node)对象。
- Map中的entry(Node)是无序的、不可重复的,使用Set存储所的entry。

map接口实现类异同点:
HashMap:作为Map的主要实现类;线程不安全的,效率高;存储null的key和value。
* LinkedHashMap:保证在遍历map元素时,可以照添加的顺序实现遍历。
* 原因:在原的HashMap底层结构基础上,添加了一对指针,指向前一个和后一个元素。
* 对于频繁的遍历操作,此类执行效率高于HashMap。
TreeMap:保证照添加的key-value键值对进行排序,实现排序遍历。此时考虑key的自然排序或定制排序。
* 底层使用红黑树。
Hashtable:作为古老的实现类;线程安全的,效率低;不能存储null的key和value。
Properties:常用来处理配置文件。key和value都是String类型。
Map接口常用方法
添加、删除、修改操作:
Object put(Object key,Object value)
:将指定key-value添加到(或修改)当前map对象中。
void putAll(Map m)
:将m中的所有key-value对存放到当前map中。
Object remove(Object key)
:移除指定key的key-value对,并返回value。
void clear()
:清空当前map中的所有数据。
元素查询的操作:
Object get(Object key)
:获取指定key对应的value。
boolean containsKey(Object key)
:是否包含指定的key。
boolean containsValue(Object value)
:是否包含指定的value。
int size()
:返回map中key-value对的个数。
boolean isEmpty()
:判断当前map是否为空。
boolean equals(Object obj)
:判断当前map和参数对象obj是否相等。
元视图操作的方法:
Set keySet()
:返回所有key构成的Set集合。
Collection values()
:返回所有value构成的Collection集合。
Set entrySet()
:返回所有key-value对构成的Set集合。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| package com.hncj.map;
import org.junit.Test;
import java.util.*;
public class MapMethodTest { @Test public void test(){ Map map = new HashMap(); map.put("AA", 123); map.put(123, 123); map.put("BB", "AA"); map.put("AA", 89); System.out.println(map); Set keys = map.keySet(); MapMethodTest.iter(keys); Collection values = map.values(); MapMethodTest.iter(values); Set entrySet = map.entrySet(); Iterator iterator = entrySet.iterator(); while (iterator.hasNext()) { Object next = iterator.next(); Map.Entry entry = (Map.Entry)next; System.out.println(entry.getKey()+"--->"+entry.getValue()); } } public static void iter(Collection coll){ Iterator iterator = coll.iterator(); while (iterator.hasNext()) { Object next = iterator.next(); System.out.println(next); } } }
|
常用方法总结:
- 增:put(Object key,Object value)
- 删:remove(Object obj)
- 改:put(Object key,Object value)
- 查:get(Object key)
- 长度:size()
- 遍历:
- Set keySet()
- Collection values()
- Set entrySet()
HashMap源码分析
HashMap 判断两个 key 相等的标准是:两个 key 哈希值相等,通过 equals() 方法返回 true。
HashMap 判断两个 value相等的标准是:两个 value 通过 equals() 方法返回 true。
HashMap的底层JDK 7和 JDK 8的区别:
JDK 7:数组+链表
JDK 8:数组+链表+红黑树
HashMap在JDK 7中实现原理:
在实例化以后,底层直接创建了长度是16的一维数组Entry[] table。
调用put()方法向HashMap中添加key-value,首先调用key所在类的hashCode()方法,计算key的哈希值,此哈希值接着通过某种算法(哈希函数/映射函数)计算出此次添加在HashMap底层数组(哈希表)中的存放位置,然后判断数组此位置上是否已经存在结点:
- 如果此位置上没有其他结点,则key-value添加成功。 —>情况1
- 如果此位置上有其他结点或以链表形式存在的多个结点(链地址法),则与其它结点的key比较hash值:
- 如果hash值不相同,则此次key-value添加成功。**—>情况2**
- 如果hash值相同,进而需要调用equals()方法比较:
- equals()返回true,则本次添加key对应的value替换原来结点的value值。
- equals()返回false,此时key-value添加成功。**—>情况3**
总结:底层也是数组,初始容量为16,当使用率超过0.75,(16*0.75=12) 且要存放的位置非空时,就会扩大容量为原来的2倍。
对于添加成功的情况2和情况3而言:元素a与已经存在此索引位置上其他数据以链表的方式存储。
HashMap在jdk8中相较于JDK 7在底层实现方面的不同:
- 在实例化以后,底层没创建一个长度为16的数组,而是在首次添加元素的时候创建。
- JDK 8底层的数组是:Node[],而非Entry[]。
- JDK 7是头插法,JDK 8为尾插法。
- JDK 8中底层使用数组+链表+红黑树实现。
- 当数组的某一个索引位置上的元素以链表形式存在的数据个数 > 8 且当前数组的长度 > 64时,此时此索引位置上的所数据改为使用红黑树存储。
HashMap源码中的重要常量:
DEFAULT_INITIAL_CAPACITY
:HashMap的默认容量,16
MAXIMUM_CAPACITY
:HashMap的最大支持容量,2^30
DEFAULT_LOAD_FACTOR
:HashMap的默认加载因子,0.75f
TREEIFY_THRESHOLD
:Bucket中链表长度大于该默认值,转化为红黑树,8。
UNTREEIFY_THRESHOLD
:Bucket中红黑树存储的Node小于该默认值,转化为链表。
MIN_TREEIFY_CAPACITY
:桶中的Node被树化时最小的hash表容量,64
table
:存储元素的数组,总是2的n次幂。
entrySet
:存储具体元素的集。
size
:HashMap中存储的键值对的数量。
modCount
:HashMap扩容和结构改变的次数。
threshold
:扩容的临界值,等于容量*填充因子。
loadFactor
:填充因子。
JDK 8底层源码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| public V put(K key, V value) { return putVal(hash(key), key, value, false, true); }
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); if (binCount >= TREEIFY_THRESHOLD - 1) treeifyBin(tab, hash); break; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } if (e != null) { V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; V value; Node<K,V> next; }
|
LinkeadHashMap源码分析
LinkedHashMap继承于HashMap,底层使用的结构与HashMap相同,重写父类的newNode()方法,在创建结点时用Entry结点替换了Node结点。
LinkedHashMap在HashMap存储结构的基础上,使用了一对双向链表来记录添加元素的顺序。
与LinkedHashSet类似,LinkedHashMap 可以维护迭代的顺序,迭代顺序与 Key-Value 对的插入顺序一致。
LinkedHashMap中的内部类:Entry
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; V value; Node<K,V> next; }
static class Entry<K,V> extends HashMap.Node<K,V> { Entry<K,V> before, after; Entry(int hash, K key, V value, Node<K,V> next) { super(hash, key, value, next); } }
|
TreeMap分析
TreeMap存储 Key-Value 对时,需要根据 key 进行排序。TreeMap 可以保证所有的 Key 处于有序状态。
TreeMap底层使用红黑树结构存储数据。
TreeMap 的 Key 的排序:
- 自然排序:TreeMap 的所有的 Key 必须实现 Comparable 接口,而且所有 的 Key 应该是同一个类的对象,否则将会抛出 ClasssCastException。
- 定制排序:创建 TreeMap 时,传入一个 Comparator 对象,该对象负责对 TreeMap 中的所有 key 进行排序。此时不需要 Map 的 Key 实现 Comparable 接口。
TreeMap判断两个key相等的标准:两个key通过compareTo()方法或者compare()方法返回0。
自然排序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public class TreeMapTest { @Test public void test(){ TreeMap treeMap = new TreeMap(); Student u1 = new Student("Jake", 19); Student u2 =new Student("Mary", 20); Student u3 =new Student("Fake", 18); Student u4 =new Student("Tom", 22); Student u5 =new Student("Jerry", 19); Student u6 =new Student("Jerry", 11); Student u7 =new Student("Jerry", 11); treeMap.put(u1, 111); treeMap.put(u2, 112); treeMap.put(u3, 113); treeMap.put(u4, 114); treeMap.put(u5, 115); treeMap.put(u6, 116); treeMap.put(u7, 117); Set entrySet = treeMap.entrySet(); Iterator iterator = entrySet.iterator(); while (iterator.hasNext()) { Object next = iterator.next(); Map.Entry map = (Map.Entry)next; System.out.println(map.getKey() + "--->" + map.getValue()); } } }
|
Student类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| import java.util.Objects;
public class Student implements Comparable{ private String name; private int age;
public Student(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; }
@Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; }
@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 compareTo(Object o) { if (o instanceof Student){ Student stu = (Student)o; int compare = -name.compareTo(stu.getName()); if(compare != 0){ return compare; } return Integer.compare(age, stu.getAge()); } throw new RuntimeException("类型不匹配!"); } }
|
定制排序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| import org.junit.Test; import java.util.*;
public class TreeMapTest { @Test public void test1(){ Comparator comparator = new Comparator() { @Override public int compare(Object o1, Object o2) { if(o1 instanceof Student && o2 instanceof Student){ Student stu1 = (Student)o1; Student stu2 = (Student)o2; int compare = Integer.compare(stu1.getAge(), stu2.getAge()); if(compare != 0) return compare; return -stu1.getName().compareTo(stu2.getName()); } throw new RuntimeException("类型不匹配!"); } }; TreeMap treeMap = new TreeMap(comparator); Student u1 = new Student("Jake", 19); Student u2 =new Student("Mary", 20); Student u3 =new Student("Fake", 18); Student u4 =new Student("Tom", 22); Student u5 =new Student("Jerry", 19); Student u6 =new Student("Jerry", 11); Student u7 =new Student("Jerry", 11); treeMap.put(u1, 111); treeMap.put(u2, 112); treeMap.put(u3, 113); treeMap.put(u4, 114); treeMap.put(u5, 115); treeMap.put(u6, 116); treeMap.put(u7, 117); Set entrySet = treeMap.entrySet(); Iterator iterator = entrySet.iterator(); while (iterator.hasNext()) { Object next = iterator.next(); Map.Entry map = (Map.Entry)next; System.out.println(map.getKey() + "--->" + map.getValue()); } } }
|
Hashtable和子类Properties
Properties概述:
- Properties 类是 Hashtable 的子类,该对象用于处理属性文件。
- 属性文件里的 key、value 都是字符串类型,所以 Properties 里的 key 和 value 都是字符串类型。
- 存取数据时,建议使用
setProperty(String key,String value)
方法和getProperty(String key)
方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| package com.hncj.map;
import java.io.FileInputStream; import java.io.IOException; import java.util.Properties;
public class PropertiesTest { public static void main(String[] args) throws IOException { Properties properties = new Properties(); FileInputStream fis = new FileInputStream("db.properties"); properties.load(fis); String name = properties.getProperty("name"); String age = properties.getProperty("age"); String hobby = properties.getProperty("hobby"); System.out.println("name="+name); System.out.println("age="+age); System.out.println("hobby="+hobby); fis.close(); } }
|
properties文件:
Collections工具类
Collections 是一个操作 Set、List 和 Map 等集合的工具类。
Collections 中提供了一系列静态的方法对集合元素进行排序、查询和修改等操作, 还提供了对集合对象设置不可变、对集合对象实现同步控制等方法。
排序操作:
reverse(List)
:反转 List 中元素的顺序。
shuffle(List)
:对 List 集合元素进行随机排序。
sort(List)
:根据元素的自然顺序对指定 List 集合元素按升序排序。
sort(List,Comparator)
:根据指定的 Comparator 产生的顺序对 List 集合元素进行排序。
swap(List,int, int)
:将指定 list 集合中的 i 处元素和 j 处元素进行交换。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| import org.junit.Test; import java.util.*;
public class CollectionsTest { @Test public void test(){ ArrayList list = new ArrayList(); list.add(123); list.add(222); list.add(111); list.add(333); list.add(12); Collections.reverse(list); System.out.println(list); Collections.shuffle(list); System.out.println(list); Collections.sort(list); System.out.println(list); Collections.sort(list, new Comparator<Integer>() { @Override public int compare(Integer i1, Integer i2) { return -i1.compareTo(i2); } }); System.out.println(list); Collections.swap(list, 2, 4); System.out.println(list); } }
|
查找、替换操作:
Object max(Collection)
:根据元素的自然顺序,返回给定集合中的最大元素。
Object max(Collection, Comparator)
:根据 Comparator 指定的顺序,返回给定集合中的最大元素。
Object min(Collection)
:根据元素的自然顺序,返回给定集合中的最小元素。
Object min(Collection, Comparator)
:根据 Comparator 指定的顺序,返回给定集合中的最小元素。
int frequency(Collection, Object)
:返回指定集合中指定元素的出现次数。
void copy(List dest, List src)
:将src中的内容复制到dest中。
boolean replaceAll(List list, Object oldVal, Object newVal)
:使用新值替换 List 对象的所有旧值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| import org.junit.Test; import java.util.*;
public class CollectionsTest { @Test public void test(){ ArrayList list = new ArrayList(); list.add(123); list.add(222); list.add(111); list.add(333); list.add(12); list.add(123); Comparable max = Collections.max(list); System.out.println(max); Comparable min = Collections.min(list); System.out.println(min); int frequency = Collections.frequency(list, 123); System.out.println(frequency); List<Object> dest = Arrays.asList(new Object[list.size()]); Collections.copy(dest, list); System.out.println(dest); Collections.replaceAll(list, 123, 888); System.out.println(list); } }
|
Collections 类中提供了多个 synchronizedXxx()
方法,该方法可使将指定集合包装成线程同步的集合,从而可以解决多线程并发访问集合时的线程安全问题。
集合实现同步操作方法:

面试题:Collection 和 Collections 的区别:
- Collection 是一个集合接口。它提供了对集合对象进行基本操作的通用接口方法。Collection接口在Java类库中有很多具体的实现。Collection接口的意义是为各种具体的集合提供了最大化的统一操作方式。
- Collections 是一个包装类。它包含有各种有关集合操作的静态多态方法。此类不能实例化,是一个操作 Set、List 和 Map 等集合的工具类。