11-Java集合

11—Java集合

1. Java集合框架概述

  • 一方面,面向对象语言对事物的体现都是以对象的形式,为了方便对多个对象的操作,就要对对对象进行存储。另一方面,使用Array存储对象方面具有一些弊端,而Java集合就像一种容器,可以动态的把多个对象引用放入容器中
    • 数组在内存存储方面的特点:
      • 数组初始化以后,长度就确定了
      • 数组声明的类型,就决定了进行元素初始化时的类型
    • 数组在存储数据方面的弊端
      • 数组初始化以后,长度就不可变了,不便于扩展
      • 数组中提供的属性和方法少,不便于进行添加、删除、插入等操作,且效率不高,无法直接获取存储元素的个数
      • 数字存储的数据是有序的、可以重复的。—>存储数据的特点单一
  • Java集合类可以用于存储数量不等的多个对象,还可以用来保存具有映射关系的关联数组
  • 使用场景
    • image-20210724151314780
  • Java集合可以分为Collection和Map两种体系
    • Collection接口:单列数据,定义了存取一组对象的方法的集合
      • List:元素有序、可重复的集合
      • Set:元素无序、不可重复的集合
      • Collection接口继承树
      • image-20210724151637427
    • Map接口:双列数据,保存具有映射关系”key=value”的集合
      • Map接口继承树
      • Inked20210724151733_LI

2. Collection接口方法

Collection接口

  • Collection接口是List、Set和Queue接口的父接口,该接口里定义的方法既可以用于操作Set集合,也可以用于操作List和Queue集合
  • JDK不提供此接口的任何直接实现,而是提供更加具体的子接口(如:Set和List)实现
  • 在Java5之前,Java集合会丢失容器中所有对象的数据类型,把所有对象都当成Object类型处理;从JDK5.0增加泛型以后,Java集合可以记住容器中对象的数据类型

Collection接口方法

  1. 添加
    1. add(Object obj)
    2. addAll(Collection coll)
  2. 删除
    1. boolean remove(Object obj):通过元素的equals方法判断是否要删除那个元素。只会删除找到的第一个元素
    2. boolean removeAll(Collection coll):取当前集合的差集
  3. 清空集合
    1. void clear()
  4. 获取有效元素的个数
    1. int size()
  5. 取两个集合的交集
    1. boolean retainAll(Collection coll):把交集的结果存在当前集合中,不影响coll
  6. 集合是否相等
    1. boolean equals(Object obj)
  7. 是否包含某个元素
    1. boolean contains(Object obj):是通过元素的equals方法来判断是否是同一个对象
    2. boolean containsAll(Collection c):也是调用元素的equals方法来比较的。拿两个集合的元素挨个比较
  8. 是否是空集
    1. boolean isEmpty()
  9. 转成对象数组
    1. Object[] toArray()
  10. 获取集合对象的哈希值
    1. hashCode()
  11. 遍历
    1. 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
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package Collection;

import org.junit.Test;

import java.util.*;

public class CollectoionTest {
@Test
public void test1(){
Collection coll1 = new ArrayList();
Collection coll2 = new ArrayList();
//添加:add(Object obj) add(Collection coll)
coll1.add(123);
coll1.add("xiong");
coll1.add(new Person("zhuo",23));
coll1.add(false);
coll1.add(new String("GUET"));

coll2.addAll(coll1);
coll2.add(new Student("sut",22,87.5));
System.out.println(coll1);//[123, xiong, Person{name='zhuo', age=23}, false, GUET]
System.out.println(coll2);//[123, xiong, Person{name='zhuo', age=23}, false, GUET, Student{name='sut', age=22, score=87.5}]

//删除:remove(Object obj) remove(Collection coll) clear()
coll1.remove(new Person("zhuo",23));
System.out.println(coll1);//[123, xiong, Person{name='zhuo', age=23}, false, GUET]
/*
结果:未能删除
原因:remove使用的是equals方法来比较二者的异同,而此时Person类中未重写equals方法,
*/
coll2.remove(new Student("sut",22,87.5));
System.out.println(coll2);//[123, xiong, Person{name='zhuo', age=23}, false, GUET]

coll1.remove(123);
coll2.removeAll(coll1);
System.out.println(coll1);//[xiong, Person{name='zhuo', age=23}, false, GUET]
System.out.println(coll2);//[123]

coll2.clear();
System.out.println(coll2);//[]

//查询:
//是否是空集:isEmpty()
System.out.println(coll2.isEmpty());//true
//获取有效元素的个数 size()
System.out.println(coll1.size());//4
//是否包含某个元素 contains(Object obj) containsAll(Collection coll) 二者也是用equals来进行比较
System.out.println(coll1.contains("xiong"));//true
System.out.println(coll1.containsAll(coll2));//true
//取两集合的交集 retainAll(Colleciton coll) 把交集结果存在当前集合中,不影响coll
Collection coll3 = Arrays.asList("xiong");
System.out.println(coll1.retainAll(coll3) + " coll1: " + coll1);//true coll1: [xiong]

//转换为数组对象 toArray()
Object[] objects = coll1.toArray();
for (Object o:
objects) {
System.out.println(o); //xiong
}

//获取对象的哈希值 hashCode
System.out.println(coll1.hashCode());//114060790

//遍历:iterator()
Iterator iter = coll1.iterator();
while (iter.hasNext()){
System.out.println(iter.next());//xiong
}
}

}
class Person{
private String name;
private int age;

public Person() { }

public Person(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 "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}

}

class Student extends Person{
private double score;
public Student() {
}

public Student(double score) {
this.score = score;
}

public Student(String name, int age, double score) {
super(name, age);
this.score = score;
}

public int getAge() {
return super.getAge();
}

public String getName(){
return super.getName();
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return this.getAge() == student.getAge() && Objects.equals(this.getName(), student.getName()) && Double.compare(student.score, score) == 0;
}

@Override
public String toString() {
return "Student{" +"name='" + super.getName() + '\'' +
", age=" + super.getAge() +
", score=" + score +
'}';
}
}

[123, xiong, Person{name=’zhuo’, age=23}, false, GUET]
[123, xiong, Person{name=’zhuo’, age=23}, false, GUET, Student{name=’sut’, age=22, score=87.5}]
[123, xiong, Person{name=’zhuo’, age=23}, false, GUET]
[123, xiong, Person{name=’zhuo’, age=23}, false, GUET]
[xiong, Person{name=’zhuo’, age=23}, false, GUET]
[123]
[]
true
4
true
true
true coll1: [xiong]
xiong
114060790
xiong

3. Iterator迭代器接口

使用Iterator接口遍历集合元素

  • Iterator对象称为迭代器(设计模式的一种),主要用于遍历Collection集合中的元素

  • GOF给迭代器模式的定义为:提供一种方法访问一个容器(container)对象中各个元素,而又不需要暴露内部细节。迭代器模式,就是为容器而生。类似于“公交车上的售票员”、”火车上的乘务员”

  • Collection接口继承了java.lang.Iterable接口,该接口有一个iterator()方法,所有实现了Collection接口的集合类都有一个iterator()方法,用以返回一个实现了Iterator对象

  • Iterator仅用于遍历集合,Iterator本身并不提供承装对象的能力。如果需要创建Iterator对象,则必须有一个被迭代的集合

  • 集合对象每次调用iterator()方法都得到一个全新的迭代器对象,默认游标都在集合的第一个元素之前

  • 在调用it.next()方法之前必须要调用it.hasNext()进行检测。若不调用,且在下一条记录无效,直接调用it.next()会抛出NoSuchElementException异常

    image-20210816175355777

  • image-20210724175448962

  • Iterator接口remove()方法

    1
    2
    3
    4
    5
    6
    7
    Iterator ter = coll.iterator();//回到起点
    while(iter.hasNext()){
    Object obj = iter.next();
    if(obj.equals("Tom")){
    iter.remove();
    }
    }
    • Iterator可以删除集合的元素,但是是遍历过程中普通迭代器对象的remove方法,不是集合对象的remove方法
    • 如果还未调用next()或在上一次调用next方法之后已经调用了remove方法,再调用remove都会报IllegalStateException

使用foreach循环遍历集合元素

  • Java5.0提供了foreach循环迭代访问Collection和数组

  • 遍历操作不需要获得Collection或数组长度,无需使用索引访问元素

  • 遍历集合的底层调用Iterator完成操作

  • foreach还可以用来遍历数组

    image-20210724180206697
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
import org.junit.Test;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class IteratorTest {
@Test
public void test1(){
Collection coll = new ArrayList();
coll.add(123);
coll.add("123");
coll.add(false);

Iterator iter = coll.iterator();

//方式一遍历
System.out.println(iter.next());
System.out.println(iter.next());
System.out.println(iter.next());

//方式二遍历
iter = coll.iterator();//每次使用迭代器都需将游标复位
for (int i = 0; i < coll.size(); i++) {
System.out.println(iter.next());
}

//方式三遍历
iter = coll.iterator();
while (iter.hasNext()){
System.out.println(iter.next());
}

//方式四遍历
for (Object c :
coll) {
System.out.println(c);
}

//方式五遍历
Object[] objects = coll.toArray();
for (int i = 0; i < objects.length; i++) {
System.out.println(objects[i]);
}

//删除集合中元素
iter = coll.iterator();
while (iter.hasNext()){
Object obj = iter.next();
if("123".equals(obj)){
iter.remove();
}
}
System.out.println(coll);
}
}

4. Collection子接口一:List

4.1 List接口概述
  • 鉴于Java中数组用来存储数据的局限性,我们通常使用List替代数组
  • List集合类中元素有序、且可重复,集合中的每个元素都有其对应的顺序索引
  • List容器中的元素都对应一个整数型的序号记载其在容器中的位置,可以根据序号存取容器中的元素
  • JDK API中List接口的实现类常用的有:ArrayList、LinkedList和Vector
4.2 List接口方法
  • List除了从Collection集合继承的方法外,List集合里添加了一些根据索引来操作集合元素的方法
    • void add(int indexm Object ele):在index位置插入ele元素
    • boolean addAll(int index, Collection eles):从index位置开始将eles中的所有元素添加进来
    • Object get(int index):获取指定index位置的元素
    • int indexOf(Object obj):返回obj在当前集合中首次出现的位置
    • int lastIndexOf(Object obj):返回obj在当前集合中末次出现的位置
    • Object set(int index, Object ele):设置指定index位置的元素为ele
    • List subList(int formIndex, 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
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
package Collection.List;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

/*
常用方法:
增:add(Object obj)
删:remove(int index) remove(Object obj)
改:set(int index, Object obj)
查:get(int index) indexOf(Object obj) lastIndexOf(Object obj)
插:add(int index, Object obj) addAll(int index, Collection coll)
长度:size()
遍历:①Iterator迭代器方式
②增强for循环
③普通循环
*/
public class ListTest {
@Test
public void test1(){
ArrayList arrayList = new ArrayList();
Collection arrayList1 = Arrays.asList("GUET",true);

//增:add(Object obj)
arrayList.add(123);
arrayList.add("xiong");
arrayList.add(false);
arrayList.add(0);
arrayList.add(arrayList1);
System.out.println(arrayList);//[123, xiong, false, 0, [GUET, true]]

//删:remove(int index, Object obj) remove(Object obj)
arrayList.remove(0);
System.out.println(arrayList);//[xiong, false, 0, [GUET, true]]
arrayList.remove(new Integer(0));
System.out.println(arrayList);//[xiong, false, [GUET, true]]

//查:get(int index) indexOf(Object obj) lastIndexOf(Object obj)
Object o = arrayList.get(1);
System.out.println(o);//false
System.out.println(arrayList.indexOf("xiong"));//0
System.out.println(arrayList.lastIndexOf("xiong"));//0

//改:set(int index, Object obj)
System.out.println(arrayList.set(1, "zhuo"));//false 返回被替换的元素
System.out.println(arrayList);//[xiong, false, [GUET, true]]

//插:add(int index, Object obj)
arrayList.add(3, "computer");
arrayList.addAll(4,arrayList1);
System.out.println(arrayList);//[xiong, zhuo, [GUET, true], computer, GUET, true]

//长度:size()
System.out.println(arrayList.size());//6

//遍历
Iterator iterator = arrayList.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}

//获取子串
System.out.println(arrayList.subList(0, 1));//[xiong] 区间为[0,1)
}
}

4.2.1 List实现类之一:ArrayList
  • Array是List接口的典型实现类、主要实现类、

  • 本质上,ArratList是对象引用的一个”变长“数组

  • ArrayList的JDK1.8之前与之后的实现区别

    • JDK1.7:ArrayList像饿汉式,直接创建一个初始容量为10的数组
    • JDK1.8:ArrayList像懒汉式,一开始直接创建一个长度为0的数组,当添加第一个元素时再创建一个容量为10的数组
  • Arrays.asList(…)方法返回的List集合,既不是ArrayList实例,也不是Vector实例。Arrays.asList(…)返回值是一个固定长度的List集合

    image-20210724214130848

4.2.2 List实现类之二:LinkedList
  • 对于频繁的插入或删除元素的操作,建议使用LinkedList类,效率较高

  • 新增方法:

    • void addFirst(Object obj)
    • void addLast(Object obj)
    • Object getFirst()
    • Object getLast()
    • Object removeFirst()
    • Object removeLast()
  • LinkedList:双向链表,内部是没有声明数组,而是定义了Node类型的first和last,用于记录首末元素。同时,定义内部类Node,作为LinkedList中保存数据的基本结构。Node除了保存数据,还定义了两个变量:

    • prev变量记录前一个元素的位置

    • next变量记录下一个元素的位置

    • 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;
          }
      }
      
      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

      ![image-20210724215014951](https://gitee.com/xiongzero/alienware_-pic-go/raw/master/img/20210724215016.png)

      ```java
      package Collection.List;

      import org.junit.Test;

      import java.util.LinkedList;

      public class LinkedListTest {
      @Test
      public void test1(){
      LinkedList linkedList = new LinkedList();
      linkedList.add(123);
      linkedList.addFirst("xiong");
      linkedList.addLast("end");
      System.out.println(linkedList);//[xiong, 123, end]

      System.out.println(linkedList.getFirst());//xiong
      System.out.println(linkedList.getLast());//end
      System.out.println(linkedList.removeFirst());//xiong
      System.out.println(linkedList);//[123, end]
      System.out.println(linkedList.removeLast());//end
      System.out.println(linkedList);//[123]
      }
      }

4.2.3 List实现类之三:Vector
  • Vector是一个古老的集合,JDK1.0就有了。大多数操作与ArrayList相同,区别之处在于Vector是线程安全的
  • 在各种list中,最好把ArryList作为缺省选择。当插入、删除频繁时,使用LinkedList;Vector总是比ArrayList慢,所以尽量避免使用
  • 新增方法:
    • void addElement(Object obj)
    • void insertElementAt(Object obj, int index)
    • void setElementAt(Object obj, int index)
    • void removeElement(Object obj)
    • void removeAllElements()
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
package Collection.List;

import org.junit.Test;

import java.util.Vector;

public class VectorTest {
@Test
public void test1(){
Vector vector = new Vector();
//增:addElement(Object obj)
vector.addElement(123);
vector.addElement("xiong");
System.out.println(vector);//[123, xiong]

//删:removeElement(Object obj)
vector.remove(new Integer(123));
System.out.println(vector);//[xiong]
vector.remove("xiong");
System.out.println(vector);//[]

//插:insertElementAt(Object obj,int index)
vector.insertElementAt("Guet",0);
System.out.println(vector);//[Guet]

//改:setElement(Object obj)
vector.set(0,"newString");
System.out.println(vector);//[newString]
}
}

面试题

请问ArrayList/LinkedList/Vector的异同?谈谈你的理解?ArrayList底层是什么?扩容机制是什么?Vector和ArrayList的最大区别?

  • ArrayList和LinkedList的异同

    二者都是线程不安全的,相对于线程安全的Vector,执行效率高。

    此外,ArrayList是实现了基于动态数组的数据结构,LinkedList基于链表的数据结构。对于随机访问get和set,ArrayList优于LinkedList,因为LinkedList要移动指针。对于新增和删除操作add(特指插入)和remove,LinkedList比较占优势,因为ArrayList要移动数据

  • ArrayList和Vector的区别

    Vector和ArrayList几乎是完全相同的,唯一的区别在于Vector是同步类(synchronized),属于强同步类。因此开销就比ArrayList要大,访问要慢。正常情况下,大多数的Java程序员使用ArrayList而不是Vector,因为同步完全可以由程序员自己控制。Vectro每次请求扩容其大小的2倍空间,而ArrayList是1.5倍。Vector还有一个子类Stack

5. Collection子接口二:Set

5.1 Set接口概述
  • Set接口是Collection的子接口,set接口没有提供给额外的方法
  • Set集合不允许包含相同的元素,如果试着把两个相同的元素加到同一个Set集合中,则添加操作失败
  • Set判断两个对象是否相同不是使用==运算符,而是根据equals()方法
5.2 Set接口方法
5.2.1 Set实现类之一:HashSet
  • HashSet是Set接口的典型实现,大多数时候使用Set集合时都使用这个实现类。
  • HashSet按Hash算法来存储集合中的元素,因此具有很好的存取、查找、删除性能
  • HashSet具有以下特点
    • 不能保证元素排列的顺序
    • HashSet不是线程安全的
    • 集合元素可以是null
  • HashSet集合判断两个元素相等的标准:两个对象通过hashCode()方法比较相等,并且两个对象的equals()方法返回值也相等
  • 对于存放在Set容器中的对象,对应的类一定要重写equals()和hasCode(Object obj)方法,以实现对象相等规则。即:”相等的对象必须有相等的散列码”
  • 向HashSet中添加元素的过程:
    • 当向HashSet集合中存入一个元素时,HashSet会调用该对象的hasCode()方法来得到该对象的hashCode值,然后根据hashCode值,通过某种散列函数决定该对象在HashSet底层数组中的存储位置。(这个散列函数会与底层数组的长度相计算得到在数组中的下表,并且这种散列函数计算还尽可能保证均匀存储元素,越是散列分布,该散列函数设计的越好
    • 如果两个元素的hashCode()值相等,会再继续调用equals方法,如果equals方法结果为true,添加失败;如果结果为false,那么会保存该元素,但是该数组的位置已经有元素了,那么会通过链表的方式继续连接
    • 如果有两个元素的equals()方法返回true,但他们的hashCode()返回值不相等,hashSet将会把他们存储在不同的位置,但依然可以添加成功
    • image-20210726145841304

重写hashCode()方法的基本原则

  • 在程序运行时,同一个对象多次调用hashCode()方法应该返回相同的值
  • 当两个对象的equals()方法比较返回true时,这两个对象的hashCode()方法的返回值也应相等
  • 对象中用作equals()方法比较的Field,都应该用来计算hashCode值

重写equals()方法的基本原则

  • 当一个类有自己特有的“逻辑相等”概念,当改写equals()的时候,总是要改写hashCode(),根据一个类的equals方法(改写后),两个截然不同的实例有可能在逻辑上是相等的,但是,根据Object.hashCode()方法,他们不仅仅是两个对象
  • 因此,违反了“相等的对象必须具有相等的散列码”
  • 结论:复写equals方法的时候一般都需要同时复写hashCode方法,通常参与计算hashCode的对象的属性也应该参与到equals()中进行计算
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
package Collection.Set;

import org.junit.Test;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;

public class HashSetTest {
@Test
public void test1(){
Set set = new HashSet();
set.add(123);
set.add("xiong");
set.add(2345);
set.add(true);

Iterator iterator = set.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}

}
}


结果不是按照添加顺序进行输出

2345
123
xiong
true

Eclipse/IDEA工具里的hashCode()的重写

以Eclipse/IDEA为例,在自定义类中可以调用工具自动重写equals和hashCode。问题:为什么用Eclipse/IDEA复写hashCode方法,有31这个数字?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Override
public int hashCode() {
return Objects.hash(name, age);
}

public static int hash(Object... values) {
return Arrays.hashCode(values);
}

public static int hashCode(Object a[]) {
if (a == null)
return 0;

int result = 1;

for (Object element : a)
result = 31 * result + (element == null ? 0 : element.hashCode());

return result;
}
  • 选择系数的收要选择尽量大的系数。因为如果计算出来的hash地址越大,所谓的“冲突”就越少。查找起来效率也会提高。(减少冲突)
  • 并且31只占用5bits,相乘造成数据溢出的概率小较小
  • 31可以由i*31==(i<<5)-1来表示,现在很多虚拟机里都有做相关优化。(提高算法效率)
  • 31是一个素数,素数的作用就是如果我用一个数字来乘以这个素数,那么最终出来的结果只能被素数本身和被乘数还有1来整除(减少冲突)
5.2.2 Set实现类之二:LinkedHashSet
  • LinkedHashSet是HashSet的子类
  • LinkedHashSet根据元素的hashCode值来确定元素的存储位置,但它同时使用双向链表维护元素的次序,这使得元素看起来是以插入顺序保存的
  • LinkedHashSet插入性能略低于HashSet,但在迭代器访问Set全部元素时有很好的性能
  • LinkedHashSet不允许集合元素重复

image-20210726152024176

  • 1
    package Collection.Set;import org.junit.Test;import java.util.Iterator;import java.util.LinkedHashSet;import java.util.Set;public class LinkedHashSetTest {    @Test    public void test1(){        Set set = new LinkedHashSet();        set.add(123);        set.add("xiong");        set.add(2345);        set.add(true);        Iterator iterator = set.iterator();        while (iterator.hasNext()){            System.out.println(iterator.next());        }    }}

结果按照添加顺序进行输出

123
xiong
2345
true

面试题:考察存储方式:先算hashCode再进行equals()

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
package Collection.Set;

import org.junit.Test;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;

public class HashSetTest {
@Test
public void test1(){
Person person1 = new Person("xiong", 23);
Person person2 = new Person("zhuo", 12);
Set set = new HashSet();
set.add(person1);
set.add(person2);
person1.setName("Guet");
set.remove(person1);
System.out.println(set);//[Person{name='Guet', age=23}, Person{name='zhuo', age=12}]

set.add(new Person("Guet",23));
System.out.println(set);//[Person{name='Guet', age=23}, Person{name='Guet', age=23}, Person{name='zhuo', age=12}]

set.add(new Person("xiong",23));
System.out.println(set);//[Person{name='Guet', age=23}, Person{name='xiong', age=23}, Person{name='Guet', age=23}, Person{name='zhuo', age=12}]


}
}

其中Person类中重写了hashCode()和equal()方法

[Person{name=’Guet’, age=23}, Person{name=’zhuo’, age=12}]
[Person{name=’Guet’, age=23}, Person{name=’Guet’, age=23}, Person{name=’zhuo’, age=12}]
[Person{name=’Guet’, age=23}, Person{name=’xiong’, age=23}, Person{name=’Guet’, age=23}, Person{name=’zhuo’, age=12}]

Set实现类之三:TreeSet
  • TreeSet是SortedSet接口的实现类,TreeSet可以确保集合元素处于排序状态。
  • TreeSet底层使用红黑树结构存储数据
  • 新增的方法如下:(了解)
    • Comparator comparator()
    • Object first()
    • Object last()
    • Object lower(Object e)
    • Object higher(Object e)
    • SortedSet subSet(fromElement, toElement)
    • SortedSet headSet(toElement)
    • SortedSet tailSet(fromElement)
  • TreeSet两种排序方法:自然排序和定制排序。默认情况下,TreeSet采用自然排序

排序——自然排序

  • 自然排序:TreeSet会调用集合元素的compareTo(Object obj)方法来比较元素之间的大小关系,然后将集合元素按升序(默认情况)排列
  • 如果试图把一个对象添加到TreeSet时,则该对象的类必须实现Comparable接口
    • 实现Comparable的类必须实现compareTo(Object obj)方法,两个对象即通过compareTo(Object obj)方法的返回值来比较大小
  • Comparable的典型实现:
    • BigDecimal、BigInteger以及所有的数值型对应的包装类:按他们对应的数值大小进行比较
    • Character:按字符的unicode值来进行比较
    • Boolean:true对应的包装类实例大于false对应包装类的实例
    • String:按字符串中字符的unicode值进行比较
    • Date、Time:后边的时间、日期比前面的时间、日期大
  • 向TreeSet中添加元素时,只有第一个元素无需比较compareTo()方法,后面添加的所有元素都会调用compareTo()方法进行比较
  • 因为只有相同类的两个实例才会比较大小,所以向TreeSet中添加的应该是同一个类的对象
  • 对于TreeSet集合而言,它判断两个对象是否相等的唯一标准是:两个对象通过compareTo(Object obj)方法比较返回值
  • 当需要把一个对象放入TreeSet中,重写该对象对应的equals()方法时,应保证该方法与compareTo(Object obj)方法有一致的结果:如果两个对象通过equals()方法比较返回true,则通过compareTo(Object obj)方法比较应该返回0

排序——定制排序

  • TreeSet的自然排序要求元素所属的类实现Comparable接口,如果元素所属的类没有实现Comparable接口,或不希望按照升序(默认情况)的方式排列元素或希望按照其他属性大小来进行排序,则考虑使用定制排序。定制排序,通过Comparator接口来实现。需要重写compare(T o1, T o2)方法
  • 利用int compare(T o1, T 02)方法,比较o1和o2的大小:如果方法返回正整数,则表示o1大于o2;如果返回负整数,表示o1小于o2
  • 要实现定制排序,需要将实现Comparator接口的实例作为形参传递给TreeSet构造器
  • 此时,仍然只能向TreeSet中添加类型相同的对象。否则发生ClassCastException异常
  • 使用定制排序判断两个元素相等的标准是:通过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
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
package Collection.Set;

import java.util.Objects;

public class Person implements Comparable{
private String name;
private int age;

public Person() {
}

public Person(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 int compareTo(Object o) {
if (this == o) return 0;
if (o == null || getClass() != o.getClass()) throw new RuntimeException("比较对象不能为空");
Person person = (Person) o;
if(this.name.compareTo(person.name) == 0){
return -Integer.compare(this.age, person.age);
}else return this.name.compareTo(person.name);
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}

@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}

@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
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
package Collection.Set;

import org.junit.Test;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class TreeSetTest {
@Test
public void test1(){
Set treeSet = new TreeSet();
treeSet.add(new Person("Tom",12));
treeSet.add(new Person("Jerry", 32));
treeSet.add(new Person("Jim",2));
treeSet.add(new Person("Mike",65));
treeSet.add(new Person("Mary",33));
treeSet.add(new Person("Jack",33));
treeSet.add(new Person("Jack",56));

System.out.println(treeSet);
//使用类实现的CompareTo()方法:按名字升序,年龄降序进行排列
Iterator iterator = treeSet.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}

@Test
public void test2(){
/*
定制排序:按照年龄升序,名字降序排列
*/
Comparator com = new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof Person && o2 instanceof Person){
Person p1 = (Person) o1;
Person p2 = (Person) o2;
int co = Integer.compare(p1.getAge(),p2.getAge());
if(co == 0){
return -p1.getName().compareTo(p2.getName());
}else return co;
}else throw new RuntimeException("传入的数据类型不匹配");

}
};
Set treeSet = new TreeSet(com);
treeSet.add(new Person("Tom",12));
treeSet.add(new Person("Jerry", 32));
treeSet.add(new Person("Jim",2));
treeSet.add(new Person("Mike",65));
treeSet.add(new Person("Mary",33));
treeSet.add(new Person("Jack",33));
treeSet.add(new Person("Jack",56));

Iterator iterator = treeSet.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}

6. Map接口

Map接口继承树

image-20210726210624429
6.1 Map接口概述
  • Map与Collection并列存在。用于保存具有映射关系的数据:key-value
  • Map中的key和value都可以是任何引用类型的数据
  • Map里的key用Set来存放,不允许重复,即同一个Map对象所对应的类,需重写hashCOde()和equals()方法
  • 常用Sting类作为Map的”键”
  • key和value之间存在单向一对一关系,即能通过指定的key总能找到唯一的、确定的value
  • Map接口的常用实现类:HashMap、TreeMap、LinkedHashMap和Properties。其中,HashMap是Map接口使用频率最高的实现类
  • image-20210726211323587
6.2 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集合
6.3 Map实现类之一:HashMap
  • HashMap是Map接口使用频率最高的实现类
  • 允许使用null键和null值,与HashSet一样,不保证映射的顺序
  • 所有的key构成的集合是Set:无序的、不可重复的。所以,key所在的类要重写:equals()和hashCode()
  • 一个key-value构成一个entry
  • 所有的entry构成的集合是Set:无序的、不可重复的
  • HashMap判断两个key相等的标准是:两个key通过equals()方法返回true,hashCode值也相等
  • HashMap判断两个value相等的标准是:两个value通过equals()方法返回true
6.3.1 HashMap的存储结构

JDK 7及以前版本:HashMap是数组+链表结构(即为链地址法)

image-20210726213049926

JDK 8版本发布以后:HashMap是数组+链表+红黑树实现。

image-20210726213131468
6.3.2 HashMap源码中的重要常量

DEFAULT_INITIAL_CAPACITY:HashMap的默认容量,16

MAXMUN_CAPACITY:HashMap的最大支持容量,2^30

DEFAULT_LOAD_FACTOR:HashMap的默认加载因子

TREEIFY_THRESHOLD:Bucket中链表长度大于该默认值,转化为红黑树

UNTREEIFY_THRESHOLD:Bucket中红黑树存储的Node小于该默认值,转化为链表

MIN_TREEIFY_CAPACITY:桶中的Node被树化时最小的hash表容量。(当桶中Node的 数量大到需要变红黑树时,若hash表容量小于MIN_TREEIFY_CAPACITY时,此时应执行 resize扩容操作这个MIN_TREEIFY_CAPACITY的值至少是TREEIFY_THRESHOLD的4 倍。)

table:存储元素的数组,总是2的n次幂

entrySet:存储具体元素的集

size:HashMap中存储的键值对的数量

modCount:HashMap扩容和结构改变的次数。

threshold:扩容的临界值,=容量*填充因子

loadFactor:填充因子

6.3.3 HashMap的存储结构:JDK 1.8之前
  • HashMap的内部存储结构其实是数组和链表的结合。当实例化一个HashMap时,系统会创建一个长度为Capacity的Entry数组,这个长度在哈希表中被称为容量(Capacity),在这个数组红可以存放元素的位置我们称为”桶“(bucket),每个bucket都有自己的索引,系统更可以更具索引快速的查找bucket中的元素
  • 每个bucket中存储一个元素,即一个Entry对象,但每一个Entry对象可以带一个引用变量,用于指向下一元素,因此,在一个桶中,就有可能生成一个Entry链。而且新添加的元素作为链表的head
  • 添加元素的过程
    向HashMap中添加entry1(key,value),需要首先计算entry1中key的哈希值(根据 key所在类的hashCode()计算得到),此哈希值经过处理以后,得到在底层Entry[]数 组中要存储的位置i。如果位置i上没有元素,则entry1直接添加成功。如果位置i上 已经存在entry2(或还有链表存在的entry3,entry4),则需要通过循环的方法,依次 比较entry1中key和其他的entry。如果彼此hash值不同,则直接添加成功。如果 hash值不同,继续比较二者是否equals。如果返回值为true,则使用entry1的value 去替换equals为true的entry的value。如果遍历一遍以后,发现所有的equals返回都 为false,则entry1仍可添加成功。entry1指向原有的entry元素。

HashMap的扩容

当HashMap中的元素越来越多的时候,hash冲突的几率也就越来越高,因为数组的 长度是固定的。所以为了提高查询的效率,就要对HashMap的数组进行扩容,而在 HashMap数组扩容之后,最消耗性能的点就出现了:原数组中的数据必须重新计算 其在新数组中的位置,并放进去,这就是resize。

那么HashMap什么时候进行扩容呢?

当HashMap中的元素个数超过数组大小(数组总大小length,不是数组中个数 size)* loadFactor 时 , 就 会 进 行 数 组 扩 容 , loadFactor 的默认 值 (DEFAULT_LOAD_FACTOR)为0.75,这是一个折中的取值。也就是说,默认情况 下,数组大小(DEFAULT_INITIAL_CAPACITY)为16,那么当HashMap中元素个数 超过16* 0.75=12(这个值就是代码中的threshold值,也叫做临界值)的时候,就把 数组的大小扩展为 2*16=32,即扩大一倍,然后重新计算每个元素在数组中的位置, 而这是一个非常消耗性能的操作,所以如果我们已经预知HashMap中元素的个数, 那么预设元素的个数能够有效的提高HashMap的性能

6.3.4 HashMap的存储结构:JDK 1.8
  • HashMap的内部存储结构其实是数组+链表+树的结合。当实例化一个 HashMap时,会初始化initialCapacity和loadFactor,在put第一对映射关系 时,系统会创建一个长度为initialCapacity的Node数组,这个长度在哈希表 中被称为容量(Capacity),在这个数组中可以存放元素的位置我们称之为 “桶”(bucket),每个bucket都有自己的索引,系统可以根据索引快速的查 找bucket中的元素。
  • 每个bucket中存储一个元素,即一个Node对象,但每一个Node对象可以带 一个引用变量next,用于指向下一个元素,因此,在一个桶中,就有可能 生成一个Node链。也可能是一个一个TreeNode对象,每一个TreeNode对象 可以有两个叶子结点left和right,因此,在一个桶中,就有可能生成一个 TreeNode树。而新添加的元素作为链表的last,或树的叶子结点。

那么HashMap什么时候进行扩容和树形化呢?

​ 当HashMap中的元素个数超过数组大小(数组总大小length,不是数组中个数 size)* loadFactor 时 , 就会进行数组扩容 , loadFactor 的默认 值 (DEFAULT_LOAD_FACTOR)为0.75,这是一个折中的取值。也就是说,默认 情况下,数组大小(DEFAULT_INITIAL_CAPACITY)为16,那么当HashMap中 元素个数超过16* 0.75=12(这个值就是代码中的threshold值,也叫做临界值) 的时候,就把数组的大小扩展为 2*16=32,即扩大一倍,然后重新计算每个元 素在数组中的位置,而这是一个非常消耗性能的操作,所以如果我们已经预知 HashMap中元素的个数,那么预设元素的个数能够有效的提高HashMap的性能。 当HashMap中的其中一个链的对象个数如果达到了8个,此时如果capacity没有 达到64,那么HashMap会先扩容解决,如果已经达到了64,那么这个链会变成 树,结点类型由Node变成TreeNode类型。当然,如果当映射关系被移除后, 下次resize方法时判断树的结点个数低于6个,也会把树再转为链表。

关于映射关系的key是否可以修改?answer:不要修改

​ 映射关系存储到HashMap中会存储key的hash值,这样就不用在每次查找时重新计算 每一个Entry或Node(TreeNode)的hash值了,因此如果已经put到Map中的映射关 系,再修改key的属性,而这个属性又参与hashcode值的计算,那么会导致匹配不上。

6.3.5 总结:JDK1.8相较于之前的变化:

1.HashMap map = new HashMap();//默认情况下,先不创建长度为16的数组

2.当首次调用map.put()时,再创建长度为16的数组

3.数组为Node类型,在jdk7中称为Entry类型

4.形成链表结构时,新添加的key-value对在链表的尾部(七上八下)

5.当数组指定索引位置的链表长度>8时,且map中的数组的长度> 64时,此索引位置 上的所有key-value对使用红黑树进行存储

面试题:负载因子值的大小,对HashMap有什么影响

  • 负载因子的大小决定了HashMap的数据密度。
  • 负载因子越大密度越大,发生碰撞的几率越高,数组中的链表越容易长, 造成查询或插入时的比较次数增多,性能会下降。
  • 负载因子越小,就越容易触发扩容,数据密度也越小,意味着发生碰撞的几率越小,数组中的链表也就越短,查询和插入时比较的次数也越小,性能会更高。但是会浪费一定的内容空间。而且经常扩容也会影响性能,建议初始化预设大一点的空间。
  • 按照其他语言的参考及研究经验,会考虑将负载因子设置为0.7~0.75,此 时平均检索长度接近于常数。
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package Map;

import org.junit.Test;

import java.util.*;

public class HashMapTest {
/*
Map提供的方法进行测试

*/
@Test
public void test1(){
Map map1 = new HashMap();
Map map2 = new HashMap();
//添加:put(Obejct key, Object value) putAll(Map m)
map1.put("xiong",23);
map1.put("zhuo", 24);
map2.putAll(map1);
System.out.println(map1);//{zhuo=24, xiong=23}
System.out.println(map2);//{zhuo=24, xiong=23}

//删除:remove(Object key) remove(Object key, Object value)
System.out.println(map1.remove("xiong"));//23
System.out.println(map1.remove("zhuo", 24));//true
System.out.println(map1);//{}

//修改:put(Object key,Object value)
System.out.println(map2.put("xiong", 22));//23
System.out.println(map2);//{zhuo=24, xiong=22}

//清空:clear()
System.out.println(map1.put("Guet", "花江"));//null
System.out.println(map1.put("Guet", "花江"));//花江
map1.clear();
System.out.println(map1);//{}

//元素查询操作
System.out.println(map2.get("xiong"));//22
System.out.println(map2.containsKey("xiong"));//true
System.out.println(map2.containsValue(22));//true
System.out.println(map2.size());//2
System.out.println(map2.isEmpty());//false
System.out.println(map2.equals(map1));//false

//元视图操作
Set set = map2.keySet();
System.out.println(set);//[zhuo, xiong]
Collection coll = map2.values();
System.out.println(coll);//[24, 22]
Set set1 = map2.entrySet();
System.out.println(set1);//[zhuo=24, xiong=22]

//遍历
//遍历所有的key集
Set set2 = map2.keySet();
Iterator iterator = set2.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());//zhuo xiong

}
//遍历所有的value集
Collection collection = map2.values();
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());//24 22
}
//遍历所有的key-value
//方式一:entrySet()
Set set3 = map2.entrySet();
iterator = set3.iterator();
while (iterator.hasNext()){
Object obj = iterator.next();
//entrySet集合中的元素都是entry
Map.Entry entry = (Map.Entry)obj;
System.out.println(entry.getKey() + "---->" + entry.getValue());
//zhuo---->24 xiong---->22
}
//方式二;
Set set4 = map2.keySet();
iterator = set4.iterator();
while (iterator.hasNext()){
Object key = iterator.next();
Object value = map2.get(key);
System.out.println(key + "--->" + value);//zhuo--->24 xiong--->22
}
}
}
6.4 Map实现类之二:LinkedHashMap
  • LinkedHashMap是HashMap的子类

  • 在HashMap存储结构的基础上,使用了一对双向链表来记录添加的顺序

  • 与LinkedHashSet类似,LinkedHashMap可以维护Map的迭代顺序:迭代顺序与Key-Value对的插入顺序一致

  • HashMap中的内部类:Node

    1
    2
    3
    4
    5
    6
    static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;
    }

    LinkedHashMap中的内部类:Entry

    1
    2
    3
    4
    5
    6
    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);
    }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    package Map;

    import org.junit.Test;

    import java.util.LinkedHashMap;
    import java.util.Map;

    public class LinkedHashMapTest {
    @Test
    public void test1(){
    Map map = new LinkedHashMap();
    map.put("zhuo",23);
    map.put("xiong",24);
    map.put("熊",23);
    System.out.println(map);//{zhuo=23, xiong=24, 熊=23}
    }
    }
6.4.1 Map实现类之三:TreeMap
  • TreeMap存储Key-Value对时,需要根据key-value对进行排序。TreeMap可以保证所有的Key-Value对处于有序状态
  • TreeSet底层使用红黑树结构存储数据
  • TreeMap的Key排序:
    • 自然排序:TreeMap的所有Key必须实现Comparable接口,而且所有的Key应该时同一个类的对象,否则将会抛出ClassCastException
    • 定制排序: 创建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
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package Map;

import org.junit.Test;

import java.util.Comparator;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

public class TreeMapTest {
@Test
public void test1(){
Map treeMap = new TreeMap();
treeMap.put(new Person("Tom",23),98);
treeMap.put(new Person("Jerry",32),89);
treeMap.put(new Person("Jack",20),76);
treeMap.put(new Person("Rose",18),100);
System.out.println(treeMap);
//{Person{name='Jack', age=20}=76, Person{name='Jerry', age=32}=89, Person{name='Rose', age=18}=100, Person{name='Tom', age=23}=98}

Comparator comparable = new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if(o1 == o2) return 0;
if(o1 == null || o2 == null || o1.getClass() != o2.getClass()) throw new RuntimeException("二者类型不匹配");
if(o1 instanceof Person && o2 instanceof Person){
Person p1 = (Person) o1;
Person p2 = (Person) o2;
int com = p1.getName().compareTo(p2.getName());
if(com != 0){
return -com;
}else return -Integer.compare(p1.getAge(),p2.getAge());
}else throw new RuntimeException("传入参数类型有误");
}
};

Map map = new TreeMap(comparable);
map.put(new Person("Tom",23),98);
map.put(new Person("Jerry",32),89);
map.put(new Person("Jack",20),76);
map.put(new Person("Rose",18),100);
System.out.println(map);
//{Person{name='Tom', age=23}=98, Person{name='Rose', age=18}=100, Person{name='Jerry', age=32}=89, Person{name='Jack', age=20}=76}

}

}

class Person implements Comparable{
private String name;
private int age;

public Person() {
}

public Person(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 int compareTo(Object o) {
if(this == o) return 0;
if(o == null || getClass() != o.getClass()) throw new RuntimeException("不同数据类型无法比较");
Person person = (Person) o;
int com = name.compareTo(person.name);
if(com != 0){
return com;
}else return Integer.compare(age, person.age);
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}

@Override
public int hashCode() {
return Objects.hash(name, age);
}

@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
6.4.2 Map实现类之四:Hashtable
  • Hashtable是一个古老的Map实现类,JDK1.0就提供了。不同于HashMap,Hashtable时线程安全的
  • Hatable实现原理和HashMap相同,功能相同。底层都使用哈希表结构,查询速度快,很多情况下可以互用
  • 与HashMap不同,Hashtable不允许使用null作为key和value
  • 与HashMap一样,Hashtable也不能保证其中Key-Value的顺序
  • Hashtable判断两个key相等、两个value相等的标准,与HashMap一致
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package Map;

import org.junit.Test;

import java.util.Hashtable;
import java.util.Map;

public class HashtableTest {
@Test
public void test1(){
Map Hashtable = new Hashtable();
Hashtable.put("xiong","tianmen");
Hashtable.put("zhuo","guangxi");
Hashtable.put("guet","huajaing");

System.out.println(Hashtable);//{zhuo=guangxi, xiong=tianmen, guet=huajaing}
}
}

6.4.3 Map实现类之五: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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package Map;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;


public class PropertiesTest {

//Properties:常用来处理配置文件。key和value都是String类型
public static void main(String[] args) {
FileInputStream fis = null;
try {
Properties pros = new Properties();

fis = new FileInputStream("C:\\Users\\xiong\\IdeaProjects\\out\\jdbc.properties");
// fis = new FileInputStream("jdbc.properties");
pros.load(fis);//加载流对应的文件

String name = pros.getProperty("name");
String password = pros.getProperty("password");

System.out.println("name = " + name + ", password = " + password);//name = 熊卓, password = abc123
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}

}
}

image-20210728112549093

7. Collections工具类

  • Collection是操作Set、List和Map等集合的工具类
  • Collections中提供了一系列静态的方法对集合元素进行排序、查询和修改等操作。还提供了对集合对象设置不可变、对集合对象实现同步控制的方法
  • 排序操作:(均为static方法)
    • reverse(List):反转List中元素的顺序
    • shuffle(List):对List集合元素进行随机排序
    • sort(List):根据元素的自然顺序对指定List集合元素按升序排序
    • sort(LIst, Comparator):根据指定的Comparator产生的顺序对List集合元素进行排序
    • swap(List, int, int):将指定list集合中的i处元素和j处元素进行交换
7.1 Collections常用方法

查找、替换

  • Object max(Collection):根据元素的自然顺序,返回给定集合中的最大元素
  • Object max(Collection, Comparator):根据Comparator指定的顺序,返回给定集合中的最大元素
  • Object min(Collection)
  • Object min(Collection, Comparator)
  • int frequency(Collection, Object):返回指定集合中指定元素的出现次数
  • void copy(List dest, List src):将src中的内容复制到dest中
  • boolean replaceAll(List list, Object oldVal, Object newVal):使用新值替换List对象的所有旧值

同步控制

Collection类中提供了多个synchronizedXxx()方法,该方法可使将指定集合包装成线程同步的集合,从而可以解决多线程并发访问集合时的线程安全问题

方法修饰符和返回值 方法
static Collection synchronizedCollection(Collection c)
Return a synchronized(thread-safe) collection backed by the spacified collection
static List synchronizedList(List list)
Return a synchronized(thread-safe)list backed by the specified list
static <K,V> Map <K,V> synchronizedMap(Map<K,V> m)
Return a synchronized(thread-safe) map backed by the specified map
static Set synchronizedSet(Set s)
Return a synchronized(thread-safe) set backed by the specified set
static <K,V> SotredMap <K,V> synchronizedSortedMap(SortedMap <K,V> m)
Return a synchronized(thread-safe)sorted map backed by the specified sorted map
static SortedSet synchronizedSortedSet(SortedSet s)
Return a synchronized(thread-safe) sorted set backed by the specified sorted 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package Collections;

import org.junit.Test;

import java.util.*;

public class CollectionsTest {
@Test
public void test1(){
List list = new ArrayList();
list.add(123);
list.add(32);
list.add(12);
list.add(45);
System.out.println(list);//[123, 32, 12, 45]

//排序
//反转
Collections.reverse(list);
System.out.println(list);//[45, 12, 32, 123]
//随机排序
Collections.shuffle(list);
System.out.println(list);//[12, 45, 123, 32]
//自然顺序升序
Collections.sort(list);
System.out.println(list);//[12, 32, 45, 123]
//按脚标交换元素
Collections.swap(list,0,2);
System.out.println(list);//[45, 32, 12, 123]

//查找、替换
System.out.println(Collections.max(list));//123
System.out.println(Collections.min(list));//12
System.out.println(Collections.frequency(list, 123));//1

//拷贝
//报异常:IndexOutOfBoundsException("Source does not fit in dest")
// List dest = new ArrayList();
// Collections.copy(dest,list);
//正确的:
List dest = Arrays.asList(new Object[list.size()]);
Collections.copy(dest,list);
System.out.println(dest);//[45, 32, 12, 123]
Collections.replaceAll(dest,123,777);
System.out.println(dest);//[45, 32, 12, 777]

//使得线程安全
List listSafe = Collections.synchronizedList(list);



}
}

补充

  • Enumeration接口时Iterator迭代器的“古老版本”
返回值类型 方法
boolean hasMoreElements()
Tests if this enumeration contains more elements
E nextElement()
Return the next element of this enumeration if this enumeration object has at least one more element to provide
1
2
3
4
Enumeration stringEnum = new StringTokenizer("a-b*c-d-e-g", "-");
while(stringEnum.hasMoreElements()){
Object obj = stringEnum.nextElement();
System.out.println(obj);