Interview [JAVA] foundation collections


1, ArrayList expansion mechanism

  1. Each time expansion is 1.5 times the original volume, achieved by shifting method.
  2. Use copyOf way for expansion.

Expansion algorithm is to first get to the pre-expansion vessel size. NewCapacity container size is then calculated by the expansion oldCapacity (oldCapacity >> 1). >> right shift operation is used here, i.e. capacity is increased 1.5 times. Also note that, when the expansion of capacity, with a time of Arrays.copyOf method is to use internal here System.arraycopy method.
the difference:

  • arraycopy () needs of the target array, the original array to array copy in your own definition, and can choose to copy the location of the start and length as well as into a new array.
  • copyOf () is the system automatically creates a new array within, and returns the array.

2, the difference between arrays and ArrayList

  1. Arrays can contain basic types, ArrayList members can only be an object.
  2. The array size is fixed, ArrayList dynamically expansion.

3, the difference between ArrayList and LinkedList

  • Thread-safe
    ArrayList and LinkedList are not synchronized, that is not guaranteed to be thread safe;
  • Data structure
    LinkedList is implemented based on a doubly linked list, ArrayList is array-based implementation.
  • Fast random access
    ArrayList supports random access, the query faster, LinkedList add, insert, delete elements faster.
  • Memory footprint
    ArrayList waste of space is mainly reflected in the list at the end of the list would reserve a certain capacity space, LinkedList using the value not only storage elements in each Node in the Node to store data, but also a reference before and after a Node a Node reference, take up more memory.
  • 遍历方式选择
    实现了RandomAccess接口的list,优先选择普通for循环 ,其次foreach,
    未实现RandomAccess接口的list, 优先选择iterator遍历(foreach遍历底层也是通过iterator实现的),大size的数据,千万不要使用普通for循环。

4、如何创建同步的List

可以通过Collections.sychronizeList将list转换成同步list,或者直接使用CopyOnWriteArrayList。

5、CopyOnWriteArrayList

  1. 读时不加锁,写入时加锁,写入时创建一个新入组将老数组拷贝进入新数组,并将数据加入新数组。
  2. 只能保证最终一致性。

6、Vector

ArrayList线程安全的一个版本,底层通过synchronize加锁实现线程安全。

7、HashMap扩容机制

HashMap使用resize()方法来进行扩容,计算table数组的新容量和Node在新数组中的新位置,将旧数组中的值复制到新数组中,从而实现自动扩容。

  1. 当空的HashMap实例添加元素时,会以默认容量16为table数组的长度扩容,此时 threshold = 16 * 0.75 = 12。
  2. 当不为空的HashMap实例添加新元素数组容量不够时,会以旧容量的2倍进行扩容,当然扩容也是大小限制的,扩容后的新容量要小于等于规定的最大容量,使用新容量创建新table数组,然后就是数组元素Node的复制了,计算Node位置的方法是 index = (n-1)

Guess you like

Origin www.cnblogs.com/clawhub/p/12064422.html