深圳幻海软件技术有限公司 欢迎您!

HashMap Key & Lmmutable类型使用原理

2023-02-28

思考,为什么我们在HashMapputkey的时候经常使用String或者Integer?A:String、Integer都是final修饰的累,都很好的重写了hashCode和equals方法,最关键的他们是Immutable类,为不可变类。可以保证hashCode的稳定性。不可变类的优点与用途1

思考,为什么我们在HashMap put key 的时候经常使用String 或者Integer?

A:String 、Integer 都是final 修饰的累,都很好的重写了 hashCode 和 equals方法,最关键的他们是Immutable类,为不可变类。可以保证hashCode的稳定性。

不可变类的优点与用途

1. 线程安全,省去了加锁的过程,因为对象内容不可变就不用担心线程同时对对象做修改

2. 拷贝效率高。当类不可变时, 拷贝其对象只需拷贝指针即可,而不用拷贝对象本身,不用担心会被修改

3. 可以作为HashMap的key,类不可变保证了Hashcode的稳定性。

如果让你实现一个自定义的class作为HashMap的key该如何实现?

A:主要关注两点即可

覆写hashCode以及equals方法应该遵循的原则

实现一个Immutable的类,那么如何实现一个不可变类呢。

1)类需要用final修饰

2)成员变量使用 private final 修饰、对外不提供set方法。

3)如果成员函数使用构造函数去接受外部的数据,成员变量,需要使用接受对象的拷贝(copy)

4)Get方法返回外部接受的成员变量,返回成员变量的拷贝(copy)

package com.jessyframe.learn;

import java.lang.String;
import java.utils.Arrays;
/**
 *
 * Created by jessy on 2022/12/24.
 */
public final class Immutable {
    private final int identity;
    private final String value;
    private final int[] arr;

    public Immutable(int identity, String value, int[] outArr) {
        this.identity = identity;
        this.value = value;
        //this.arr = outArr; //不正确
        this.arr = outArr.clone();//使用传入数组的copy初始化
    }

    public int[] getArr() {
        //return arr; //不正确
        return arr.clone(); //返回数组的copy
    }

     
        public static void main(String[] args) {
        int[] arr = new int[]{12,34};
        Immutable im = new Immutable(123,"jessyframe", arr);
        int[] arr1 = im.getArr();
        Arrays.stream(arr1).forEach((e) -> {System.out.println(e);});
        arr[0] = 56;
        arr[1] = 78;
        Arrays.stream(arr1).forEach((e) -> {System.out.println(e);});
    }

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