ArrarList&HashMap, 这些基础你还记得吗?
来源:互联网 发布:svm算法原理 编辑:程序博客网 时间:2024/06/05 14:30
ArrarList
创建:
new ArrayList();
下面这是一个ArrayList默认构造方法的源代码,他只进行了一次赋值操作,这里的this.elementData则是Array List中的数据存储表,也就是一个Object[],其中,DEFAULTCAPACITY_EMPTY_ELEMENTDATA是一个静态的公共的Object[],从这段代码可以证明在创建ArrayList的时候,当前实例会默认得到一个固定长度的数组。
/** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; }
添加元素:
ArrayList.add();
这个ArrayList在创建并得到初始的数组容器后,当添加的内容超过这个数组容器本身的长度后会如何?
我的回答是当超过Array List内部数组本身长度后,他会new一个新的、更长的数组,同时,吧旧数组的内容再重新赋值给新的数组中去,并将this.elementData指针指向新的数组。
且看下面JDK源码,这段代码中执行了这么一句话ensureCapacityInternal(size + 1):
/** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */ public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; }
那么这个ensureCapacityInternal()方法就是得到下一个坐标,当下一个坐标超过数组界限是,就会触发new新数组的过程了,如下:
private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity);}private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity);}
从上面代码会发现,当if (minCapacity - elementData.length > 0)时,也就是数组不够时,会触发grow()方法(创建新数组并将旧数组的值复制到新的数组容器中去),JDK代码如下:
/** * Increases the capacity to ensure that it can hold at least the * number of elements specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity */ 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); }
证明:
以上代码证明,我的理解是正确的,并且从这整个流程中可以看出,ArrayList本身也是一个线程不安全的集合,他缺失了原子性。那么如何让他线程安全呢?我使用synchronized修饰add方法和get方法可以使ArrayList变得线程安全。
另外,问道我除了ArrayList之外,用其他的集合方式能否实现线程安全,我只到有那么一个集合,和Array List非常相似,但当时一直没有想起是什么来,因为我几乎没有用到这个类,其实他叫Vector,这里我给出的解释是:
因为ArrayList本身是基于数组的一个List,所以他的查询性能不需质疑,但对于存储性能来说,因为他在存储的时候可能会重新计算索引,所以在存储性能上其实是比较浪费资源的,尤其是在并发场景下,所以一般情况下我用ArrayList都是在单线程中去使用,更多的是用它来承载列表数据。也没有遇到过硬性需求使我必须在多线程的场景下使用ArrayList,如果有这个需求,我会选择前者(修饰add和get方法使其同步)因为在Vector中,也是这么做的。并且Java官方也并不是很鼓励大量使用Vector。
HashMap
HashMap是一个基于哈希表的集合
创建:
new HashMap();
再JVM中,默认存在一个HashMap的初始因子,他的值时0.75f
/** * The load factor used when none specified in constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f;
当调用HashMap的构造方法时,他执行了下面代码,这段代码就是给当前实例的哈希表设置一个初始因子(这也就是所谓的哈希表了,而这也是他的核心,下面的存取操作也是基于这里的哈希表):
/** * Constructs an empty <tt>HashMap</tt> with the default initial capacity * (16) and the default load factor (0.75). */ public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted }
赋值:
Map.put(key, value);
源代码:
/** * Associates the specified value with the specified key in this map. * If the map previously contained a mapping for the key, the old * value is replaced. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt>. * (A <tt>null</tt> return can also indicate that the map * previously associated <tt>null</tt> with <tt>key</tt>.) */ public V put(K key, V value) { return putVal(hash(key), key, value, false, true); }
其中,hash(key)这个函数的作用是,将用户所传入的key计算成一个值,这个值我叫他哈希值,int类型,他对应的这个值的内存的对应的数据,也就是value,所以,当put一个重复的key时,他的哈希值计算结果时相同的,那么效果就是,key不变,value被覆盖。
证明:
这是hash函数的源代码,他得到了key的hashCode,同时为了避免在内存中不同实例所在内存的key的冲突,又进行了二次计算
/** * Computes key.hashCode() and spreads (XORs) higher bits of hash * to lower. Because the table uses power-of-two masking, sets of * hashes that vary only in bits above the current mask will * always collide. (Among known examples are sets of Float keys * holding consecutive whole numbers in small tables.) So we * apply a transform that spreads the impact of higher bits * downward. There is a tradeoff between speed, utility, and * quality of bit-spreading. Because many common sets of hashes * are already reasonably distributed (so don't benefit from * spreading), and because we use trees to handle large sets of * collisions in bins, we just XOR some shifted bits in the * cheapest possible way to reduce systematic lossage, as well as * to incorporate impact of the highest bits that would otherwise * never be used in index calculations because of table bounds. */static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);}
得到之前的key的哈希值后,直接找出他的value存储位置,并创建Node(key、Value),这个时候,赋值操作就完成了,当然在其中还会有很多场景下的健壮性处理。
这是put函数的源代码,这也是HashMap允许存储null值以及可能get出null的原因:
/** * 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. * @return previous value, or null if none */ 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) // -1 for 1st treeifyBin(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 key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
取值:
下面两个函数,也证明了以上观点,他在取值时,会根据传入的key计算出hash值,并拿到这个Node所在的位置,然后获得这个node的value。
/** * Returns the value to which the specified key is mapped, * or {@code null} if this map contains no mapping for the key. * * <p>More formally, if this map contains a mapping from a key * {@code k} to a value {@code v} such that {@code (key==null ? k==null : * key.equals(k))}, then this method returns {@code v}; otherwise * it returns {@code null}. (There can be at most one such mapping.) * * <p>A return value of {@code null} does not <i>necessarily</i> * indicate that the map contains no mapping for the key; it's also * possible that the map explicitly maps the key to {@code null}. * The {@link #containsKey containsKey} operation may be used to * distinguish these two cases. * * @see #put(Object, Object) */public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value;}/** * Implements Map.get and related methods * * @param hash hash for key * @param key the key * @return the node, or null if none */final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null;}
以上证明,我的回答是完全整却的!其实当时我也不是很确定我的回答是否正确,因为一直到现在我都在想办法学习新的东西例如分布式这是真的,一些基础的东西可能记忆有些模糊了,直到我今天又翻了源码。
在此贴出文章,在面试的过程中,如果有面试官再问到你这两个集合的问题时,咱们可以大声地喊出来,不要犹豫,对的就是对的。错的对不了,对的错不了。我就是因为当时不确定而丧失了一次机会。。。
- ArrarList&HashMap, 这些基础你还记得吗?
- [零基础学Python]字典,你还记得吗?
- 你还记得我吗?
- 安卓 10 周岁了:这些消失的经典 APP 你还记得吗?
- 还记得你的职业梦想吗
- 那些微笑,你还记得吗
- 乡愁,你还记得我吗?
- java基础数据类型(你还记得几个)
- JAVA面试题解惑系列(十一)——这些运算符你是否还记得?
- JAVA面试题解惑系列(十一)——这些运算符你是否还记得?
- JAVA面试题解惑系列(十一)——这些运算符你是否还记得?
- JAVA面试题解惑系列(十一)——这些运算符你是否还记得?
- JAVA面试题解惑系列(十一)——这些运算符你是否还记得?
- JAVA面试题解惑系列(十一)——这些运算符你是否还记得?
- JAVA面试题解惑系列(十一)——这些运算符你是否还记得?
- JAVA面试题解惑系列(十一)——这些运算符你是否还记得?
- JAVA面试题解惑系列(十一)——这些运算符你是否还记得?
- JAVA面试题解惑系列(十一)——这些运算符你是否还记得?
- Cent OS 7 添加 EPEL Nux Dextop ELRepo等源
- 工厂模式
- ZCMU1261
- 素数
- linxu 驱动 DEVICE_ATTR和device_create_file 学习实例
- ArrarList&HashMap, 这些基础你还记得吗?
- 一些常用的JVM参数
- java-旋转数组的最小数字
- NanoPi用网线与电脑直连
- 关于处理按键长按不用onKeyLongPress的另一种解决方案
- “马师傅”告诉你,有钱就可以为所欲为!
- spring四种依赖注入方式
- 如何使用Properties配置文件
- mysql备份与恢复(一)