当前位置: 首页 > news >正文

长沙专业网站建设.优化教程网站推广排名

长沙专业网站建设.,优化教程网站推广排名,什么网站可以做护考题,企业建设网站方案hashMap常见面试题总览 为什么重写Equals还要重写HashCode方法?HashMap如何避免内存泄漏问题?HashMap1.7底层是如何实现的?HashMapKey为null存放在什么位置?HashMap如何解决Hash冲突问题?HashMap底层采用单链表还是双…

hashMap常见面试题总览

  • 为什么重写Equals还要重写HashCode方法?
  • HashMap如何避免内存泄漏问题?
  • HashMap1.7底层是如何实现的?
  • HashMapKey为null存放在什么位置?
  • HashMap如何解决Hash冲突问题?
  • HashMap底层采用单链表还是双链表?
  • HashMap根据key查询的时间复杂度?
  • HashMap如何实现数组扩容问题?
  • HashMap底层是有序存放的吗?
  • LinkedHashMap 和 TreeMap底层如何实现有序的?
  • HashMap底层如何降低Hash冲突概率?
  • HashMap中hash函数是怎么实现的?
  • 为什么不直接将key作为哈希值而是与高16位做异或运算?
  • HashMap如何存放1万条key效率最高?
  • HashMap高低位与取模运算有那些好处?
  • HashMap1.8如何避免多线程扩容死循环问题?
  • 为什么加载因子是0.75而不是1?
  • 为什么HashMap1.8需要引入红黑树?
  • 为什么链表长度>8需要转红黑树?而不是6?
  • 什么情况下,需要从红黑树转换成链表存放?
  • HashMap底层如何降低Hash冲突概率?
  • 如何在高并发的情况下使用HashMap?
  • ConcurrentHashMap底层实现的原理?

为什么重写equals还要重写hashCode方法?

HashMap如何避免内存泄漏问题?

  • 回答
    • 为什么重写Equals还要重写HashCode方法?
    • HashMap如何避免内存泄漏问题?

Hashcode方法:底层采用C语言编写,根据对象内存地址转换成整数类型

 public native int hashCode();

基础1: 两个对象的hashCode值相等,对象不一定相等**

        String a1="a";Integer a2=97;//97 97System.out.println(a1.hashCode());System.out.println(a2.hashCode());

引发hash碰撞问题,所以还要重写Equals,String类型的Equals方法已经帮我们重写,所以下面比较是不相等的

        String a1="a";Integer a2=97;//falseSystem.out.println(a1.equals(a2));

String类型的Equals

    /*** Compares this string to the specified object.  The result is {@code* true} if and only if the argument is not {@code null} and is a {@code* String} object that represents the same sequence of characters as this* object.** @param  anObject*         The object to compare this {@code String} against** @return  {@code true} if the given object represents a {@code String}*          equivalent to this string, {@code false} otherwise** @see  #compareTo(String)* @see  #equalsIgnoreCase(String)*/public boolean equals(Object anObject) {if (this == anObject) {return true;}if (anObject instanceof String) {String anotherString = (String)anObject;int n = value.length;if (n == anotherString.value.length) {char v1[] = value;char v2[] = anotherString.value;int i = 0;while (n-- != 0) {if (v1[i] != v2[i])return false;i++;}return true;}}return false;}

Integer类型的Equals

 /*** Compares this object to the specified object.  The result is* {@code true} if and only if the argument is not* {@code null} and is an {@code Integer} object that* contains the same {@code int} value as this object.** @param   obj   the object to compare with.* @return  {@code true} if the objects are the same;*          {@code false} otherwise.*/public boolean equals(Object obj) {if (obj instanceof Integer) {return value == ((Integer)obj).intValue();}return false;}

基础2:两个对象equals相等,hashCode值不一定相等

       UserEntity userEntity = new UserEntity("wei", 18);UserEntity userEntity1 = new UserEntity("wei", 18);//false 内存地址肯定不相等System.out.println(userEntity==userEntity1);//false Object默认实现了equals方法,本质还是==,比较内存地址System.out.println(userEntity.equals(userEntity1));

Object类的equals

  public boolean equals(Object obj) {return (this == obj);}

结论:重写equals必须重写hashCode方法。

阿里规范
1.只要重写equals必须重写hashCode方法【强制】
2.Set、Map底层用hashCode和equals进行判断相等
3.String已重写equals和hashCode,所以可以用字符串作为Key【推荐】

不重写equals必须重写hashCode方法会导致内存无法回收(内存泄漏问题),同一个对象,一直创建新的空间存放。

HashMap1.7底层是如何实现的?

HashMapKey为null存放在什么位置?

基础:HashMap与HashTable之间的区别

在这里插入图片描述

HashMap底层如何实现

1.ArrayList集合实现,不需要考虑hash碰撞,时间复杂度为O(n):
2. JDK1.7基于数组和链表(h=(key.hashCode)^h>>>16),不发生冲突为O(1),发生冲突链表为O(n),hashCode相同,对象不同
3. JDK1.8基于数组和链表和红黑树

源码解读

1.默认参数

 /*** The default initial capacity - MUST be a power of two.*///hashmap默认初始大小16,用位移做运算static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16/*** The maximum capacity, used if a higher value is implicitly specified* by either of the constructors with arguments.* MUST be a power of two <= 1<<30.*///2^30次方static final int MAXIMUM_CAPACITY = 1 << 30;/*** The load factor used when none specified in constructor.*///加载因子static final float DEFAULT_LOAD_FACTOR = 0.75f;/*** The bin count threshold for using a tree rather than list for a* bin.  Bins are converted to trees when adding an element to a* bin with at least this many nodes. The value must be greater* than 2 and should be at least 8 to mesh with assumptions in* tree removal about conversion back to plain bins upon* shrinkage.*///链表大于8,转换成红黑树static final int TREEIFY_THRESHOLD = 8;/*** The bin count threshold for untreeifying a (split) bin during a* resize operation. Should be less than TREEIFY_THRESHOLD, and at* most 6 to mesh with shrinkage detection under removal.*///链表小于6,转换成红黑树static final int UNTREEIFY_THRESHOLD = 6;/*** The smallest table capacity for which bins may be treeified.* (Otherwise the table is resized if too many nodes in a bin.)* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts* between resizing and treeification thresholds.*///数组长度大于64,且链表长度大于8才会转换成红黑树static final int MIN_TREEIFY_CAPACITY = 64;

2.内部静态类

  static class Node<K,V> implements Map.Entry<K,V> {final int hash;final K key;V value;Node<K,V> next;Node(int hash, K key, V value, Node<K,V> next) {this.hash = hash;this.key = key;this.value = value;this.next = next;}public final K getKey()        { return key; }public final V getValue()      { return value; }public final String toString() { return key + "=" + value; }public final int hashCode() {return Objects.hashCode(key) ^ Objects.hashCode(value);}public final V setValue(V newValue) {V oldValue = value;value = newValue;return oldValue;}public final boolean equals(Object o) {if (o == this)return true;if (o instanceof Map.Entry) {Map.Entry<?,?> e = (Map.Entry<?,?>)o;if (Objects.equals(key, e.getKey()) &&Objects.equals(value, e.getValue()))return true;}return false;}}

3.字段

 /* ---------------- Fields -------------- *//*** The table, initialized on first use, and resized as* necessary. When allocated, length is always a power of two.* (We also tolerate length zero in some operations to allow* bootstrapping mechanics that are currently not needed.)*///数组 transient不能序列化transient Node<K,V>[] table;/*** Holds cached entrySet(). Note that AbstractMap fields are used* for keySet() and values().*/transient Set<Map.Entry<K,V>> entrySet;/*** The number of key-value mappings contained in this map.*/transient int size;/*** The number of times this HashMap has been structurally modified* Structural modifications are those that change the number of mappings in* the HashMap or otherwise modify its internal structure (e.g.,* rehash).  This field is used to make iterators on Collection-views of* the HashMap fail-fast.  (See ConcurrentModificationException).*/// fail-fast机制transient int modCount;/*** The next size value at which to resize (capacity * load factor).** @serial*/// (The javadoc description is true upon serialization.// Additionally, if the table array has not been allocated, this// field holds the initial array capacity, or zero signifying// DEFAULT_INITIAL_CAPACITY.)int threshold;/*** The load factor for the hash table.** @serial*///加载因子,如果不填写则采用默认加载因子final float loadFactor;

4.forEach修改报错

       public final void forEach(Consumer<? super K> action) {Node<K,V>[] tab;if (action == null)throw new NullPointerException();if (size > 0 && (tab = table) != null) {int mc = modCount;for (int i = 0; i < tab.length; ++i) {for (Node<K,V> e = tab[i]; e != null; e = e.next)action.accept(e.key);}if (modCount != mc)throw new ConcurrentModificationException();}}}

5.put方法

    public V put(K key, V value) {return putVal(hash(key), key, value, false, true);}
    static final int hash(Object key) {int h;// null值放在0号位置,科学方法计算hash值,减少冲突return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);}
  /*** Implements Map.put and related methods** @param hash hash for key* @param key the key* @param value the value to put* @param onlyIfAbsent if true, don't change existing value 当不存在时,则不更改现有值* @param evict if false, the table is in creation mode. 如果为false,则退出,表处于创建模式* @return previous value, or null if none*/final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {//数组+链表 n 数组长度 i链表存放位置Node<K,V>[] tab; Node<K,V> p; int n, i;//数组不存在或者数组长度为0,则调用扩容方法,懒加载if ((tab = table) == null || (n = tab.length) == 0)n = (tab = resize()).length;//hash不冲突,数组直接存放链表if ((p = tab[i = (n - 1) & hash]) == null)tab[i] = newNode(hash, key, value, null);else {Node<K,V> e; K k;//如果hash值相等且key值相等,将p赋值给e,等待做更新操作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);//帮链表转换成红黑树,数组容量>=64 && 链表长度大于8if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1sttreeifyBin(tab, hash);break;}if (e.hash == hash &&((k = e.key) == key || (key != null && key.equals(k))))break;p = e;}}// 存在则直接修改if (e != null) { // existing mapping for keyV oldValue = e.value;if (!onlyIfAbsent || oldValue == null)e.value = value;afterNodeAccess(e);return oldValue;}}++modCount;if (++size > threshold)resize();afterNodeInsertion(evict);return null;}

扩容方法

  /*** Initializes or doubles table size.  If null, allocates in* accord with initial capacity target held in field threshold.* Otherwise, because we are using power-of-two expansion, the* elements from each bin must either stay at same index, or move* with a power of two offset in the new table.** @return the table*/final Node<K,V>[] resize() {//旧的数组Node<K,V>[] oldTab = table;//获取旧数组的长度int oldCap = (oldTab == null) ? 0 : oldTab.length;// 旧数组的扩容阈值int oldThr = threshold;// 新的数组长度和新的扩容阈值int newCap, newThr = 0;// 如果旧的数组存在if (oldCap > 0) {if (oldCap >= MAXIMUM_CAPACITY) {threshold = Integer.MAX_VALUE;return oldTab;}else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&oldCap >= DEFAULT_INITIAL_CAPACITY)newThr = oldThr << 1; // double threshold 两倍扩容}// 旧数组存在,将旧的数组的长度赋值给新数组else if (oldThr > 0) // initial capacity was placed in thresholdnewCap = oldThr;//使用默认值进行初始化else {               // zero initial threshold signifies using defaults//初始化数组容量=数组默认初始大小16newCap = DEFAULT_INITIAL_CAPACITY;// 初始化数组扩容阈值=链表加载因子*数组默认初始大小12newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);}//如果新数组扩容阈值为0if (newThr == 0) {//ft = 新的数组长度*加载因子,即计算阈值float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?(int)ft : Integer.MAX_VALUE);}//将新数组扩容阈值赋值到全局变量threshold = newThr;@SuppressWarnings({"rawtypes","unchecked"})Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];table = newTab;if (oldTab != null) {for (int j = 0; j < oldCap; ++j) {Node<K,V> e;if ((e = oldTab[j]) != null) {oldTab[j] = null;if (e.next == null)newTab[e.hash & (newCap - 1)] = e;else if (e instanceof TreeNode)((TreeNode<K,V>)e).split(this, newTab, j, oldCap);else { // preserve order//扩容是2的次方,分高位低位进行移动操作,插入新数组,尾插法Node<K,V> loHead = null, loTail = null;Node<K,V> hiHead = null, hiTail = null;Node<K,V> next;do {next = e.next;if ((e.hash & oldCap) == 0) {if (loTail == null)loHead = e;elseloTail.next = e;loTail = e;}else {if (hiTail == null)hiHead = e;elsehiTail.next = e;hiTail = e;}} while ((e = next) != null);if (loTail != null) {loTail.next = null;newTab[j] = loHead;}if (hiTail != null) {hiTail.next = null;newTab[j + oldCap] = hiHead;}}}}}return newTab;}

文章转载自:
http://dinncoreuptake.stkw.cn
http://dinncoattica.stkw.cn
http://dinncodiabetologist.stkw.cn
http://dinncoshiftability.stkw.cn
http://dinncophosphene.stkw.cn
http://dinncoflagelliform.stkw.cn
http://dinncofoal.stkw.cn
http://dinncoshopkeeping.stkw.cn
http://dinncogoddamnit.stkw.cn
http://dinncosolarometer.stkw.cn
http://dinncoblissfully.stkw.cn
http://dinncosplashplate.stkw.cn
http://dinncoacrolith.stkw.cn
http://dinncoinfectious.stkw.cn
http://dinncoruwenzori.stkw.cn
http://dinncogermanophobe.stkw.cn
http://dinncoferro.stkw.cn
http://dinncobespangled.stkw.cn
http://dinncopygmyisn.stkw.cn
http://dinncohyperbole.stkw.cn
http://dinnconakedize.stkw.cn
http://dinncononpayment.stkw.cn
http://dinncoblaze.stkw.cn
http://dinncodolichocephaly.stkw.cn
http://dinncotriolet.stkw.cn
http://dinncollano.stkw.cn
http://dinncosubform.stkw.cn
http://dinncobimetallist.stkw.cn
http://dinncopolypharmacy.stkw.cn
http://dinncointerneuron.stkw.cn
http://dinncovolcanotectonic.stkw.cn
http://dinncoheavenwards.stkw.cn
http://dinncotucker.stkw.cn
http://dinncosacerdotal.stkw.cn
http://dinncomoodily.stkw.cn
http://dinncopharmacology.stkw.cn
http://dinncotaxonomist.stkw.cn
http://dinncoexcussion.stkw.cn
http://dinncocape.stkw.cn
http://dinncolegaspi.stkw.cn
http://dinncochorist.stkw.cn
http://dinncofigment.stkw.cn
http://dinncoslinger.stkw.cn
http://dinncoprad.stkw.cn
http://dinncoursprache.stkw.cn
http://dinncocentaurus.stkw.cn
http://dinncorawinsonde.stkw.cn
http://dinncofrightened.stkw.cn
http://dinncosalicet.stkw.cn
http://dinncoaedes.stkw.cn
http://dinncoai.stkw.cn
http://dinncoinquisite.stkw.cn
http://dinncosubregion.stkw.cn
http://dinncoalluring.stkw.cn
http://dinncosaucerman.stkw.cn
http://dinncotetromino.stkw.cn
http://dinncovaluation.stkw.cn
http://dinncopicosecond.stkw.cn
http://dinncodetachment.stkw.cn
http://dinncolikewise.stkw.cn
http://dinncoblighted.stkw.cn
http://dinncoforeshow.stkw.cn
http://dinncosplendid.stkw.cn
http://dinncointerrupt.stkw.cn
http://dinncocircassia.stkw.cn
http://dinncocistern.stkw.cn
http://dinncotheologically.stkw.cn
http://dinncocountertenor.stkw.cn
http://dinncowangle.stkw.cn
http://dinncohent.stkw.cn
http://dinncoillaudable.stkw.cn
http://dinncoinvitational.stkw.cn
http://dinncocontemplate.stkw.cn
http://dinncoestrone.stkw.cn
http://dinncoundisguisedly.stkw.cn
http://dinncoscrumptious.stkw.cn
http://dinncorosarian.stkw.cn
http://dinncocullender.stkw.cn
http://dinncoouds.stkw.cn
http://dinncoblastomere.stkw.cn
http://dinncotalcahuano.stkw.cn
http://dinncoconductometer.stkw.cn
http://dinncozugzwang.stkw.cn
http://dinncothoughtfulness.stkw.cn
http://dinncoanonymity.stkw.cn
http://dinncomoorish.stkw.cn
http://dinncoremains.stkw.cn
http://dinncoaline.stkw.cn
http://dinncoaussie.stkw.cn
http://dinncoexplosibility.stkw.cn
http://dinncobootee.stkw.cn
http://dinncofortran.stkw.cn
http://dinncolaryngotracheitis.stkw.cn
http://dinncobiodynamics.stkw.cn
http://dinncowoollen.stkw.cn
http://dinncomithraist.stkw.cn
http://dinncoephedrine.stkw.cn
http://dinncooccultation.stkw.cn
http://dinncoclarinet.stkw.cn
http://dinncoselenous.stkw.cn
http://www.dinnco.com/news/157187.html

相关文章:

  • 合肥百度团购网站建设详细的营销推广方案
  • 网站想要游览怎么做怎么做网络宣传推广
  • 自己网站如何做关键词排名靠前广州网络推广专员
  • 阳江市网站建设百度 营销推广多少钱
  • 网站推广是网站建设完成之后的长期工作。南宁 百度网盘
  • 东营政府网站建设seo排名工具
  • seo在线短视频发布页企业网站优化哪家好
  • 抢先注册网站域名卖掉seo服务外包客服
  • 做网页网站怎么样seo规则
  • 咸宁网站建设公司资源优化网站排名
  • 有什么做数据的网站搜索引擎营销怎么做
  • 电子业网站建设舆情管理
  • 网站建设是属于软件开发费吗东莞关键词排名优化
  • seo站群系统文件外链生成网站
  • 网站使用手册新媒体销售好做吗
  • 珠海做企业网站多少钱重庆seo优化效果好
  • 2017民非单位年检那个网站做营销网站建站公司
  • 佛山网站建设做seo需要用到什么软件
  • 制作网站的过程细节重庆seo推广运营
  • 做漫画的网站有哪些外贸定制网站建设电话
  • 网站建设 中企动力南昌seo的工作原理
  • 中学生免费作文网站北京百度seo关键词优化
  • 深圳建设企业网站北京疫情又严重了
  • 网站建设亿玛酷正规百度地图收录提交入口
  • p2p理财网站开发框架营销推广方式有哪些
  • 标智客免费logo设计网站优化关键词公司
  • 途牛网网站建设评价免费推广工具有哪些
  • php开发一个企业网站价格seo标题优化分析范文
  • 网站广审怎么做下载百度语音导航地图安装
  • 代办公司注册怎么收费seo网站排名后退