-java collection of interviews knowledge "I have heard very good use of the most complete history" Daquan

Welcome attention to this series of articles, learn together
to enhance the ability salary increase may be
interviewing knowledge, work can be
practical exercise, rejected 996
also welcome public concern number [ Ccww notes ], the first time the introduction of original technology articles
if you have this article help, like it, then point a praise chant, point followers chant!

A collection of foundation

What are the advantages set framework 1.1 is as follows:

  • The use of core collections to reduce development costs, rather than to achieve our own collection classes.
  • With the use of a set of class-tested framework, code quality will be improved.
  • By using JDK collections so, you can reduce code maintenance costs.
  • Reusability and maneuverability.

Basic Interface 1.2 Java collections framework of what?

Java collection classes provides a set of well-designed support for the operation of a set of objects interfaces and classes. Java collection classes inside the most basic interfaces:

  • Collection: on behalf of a group of objects, each object is its children.
  • Set: does not contain duplicate elements Collection.
  • List: There collection order and may contain repeated elements.
  • Map: The key may be (key) is mapped to the target value (value), the key can not be repeated.
  • There are other interfaces Queue, Dequeue, SortedSet, SortedMap and ListIterator.

1.3 Why does not implement Cloneable class collection and Serializable interface?

Collections interface specifies a set of objects, called elements. Each specific category collections interface can choose its own way to save and sorting elements, such collections can be very flexible, can implement a custom collection class attributes, such as some collections allow duplicate key some do not.

1.4 Collections Framework Generics What are the advantages?

Java5 introduces a generic, all the collection interfaces and implementations use a lot of it. Generics allow us to offer a type of object that can be accommodated for the collection. So, if you add any other type of element, it will complain at compile time. This avoids the appearance ClassCastException at run time, because you will get an error message at compile time.

Generic clean also makes the code, we do not use the explicit conversion and instanceOf operator. It also brings benefits to running, because no type checking of bytecode instructions.

1.5 Collection and Collections of the difference?

  • Collection, is a collection of superior class interfaces, inheritance and his main interface Set and List.
  • Collections, is a collection of tools for a class, it offers a range of static methods to achieve a variety of search collection, sorting, and so thread-safe operations.

1.6 What is an iterator (Iterator)?

Iterator interface provides many ways to iterate over the elements of the collection. Each class contains a collection iterative method may return an iterator instance. Iterator can remove an element of the underlying collection during iteration.

Clone (Cloning) or a sequence of (serialization) semantics and meaning associated with a specific implementation. Therefore, it should be determined by the specific implementation classes is how to clone or serialized.

What is the difference 1.7 Iterator and ListIterator is?

Their differences are listed below:

  • Iterator used to iterate Set and List collections, but can only be used to traverse ListIterator List.
  • Iterator of the collection can only be traversed forward, ListIterator both before to be backward.
  • ListIterator implements Iterator interface, and include other features, such as: adding elements to replace elements, obtaining an index before and after an element, and so on.

1.8 What is the difference between fast failure (fail-fast) and the security failure (fail-safe) is?

Iterator safety is based on a failure to make copies of the underlying collection, therefore, it is not the impact of the changes source set.

java.util package following all the collections are fail-fast, and java.util.concurrent package all of the following classes are safe to fail. Fail-fast iterator will throw ConcurrentModificationException exception, fail safe iterator will never throw this exception.

The difference between 1.9 Enumeration interface and the interface Iterator What?

Enumeration Iterator twice the speed, but uses less memory. However, Iterator far from able to modify the set of objects which are being traversed iterator than Enumeration safety, because other threads. Meanwhile, Iterator allows the caller to delete the underlying collection elements inside, which Enumeration is impossible.

Best Practice 1.10 Java collections framework of what?

Applications need to be properly selected according to the type of collection you want to use is very important to the performance, such as: if the size of the element is fixed, and can know in advance, we should use Array instead of ArrayList. Some collection class allows you to specify the initial capacity. Thus, if we can estimate the number of storage elements, we can set the initial capacity to avoid re-calculated hash values ​​or expansion.

For the type of security, readability and robustness of the reason is always to use generics. At the same time, the use of generics also avoid ClassCastException at runtime.

Use the same class (immutable class) JDK supplied as Map keys to avoid our own class implements hashCode () and equals () method.

When programming interface to achieve superior.

Is actually a set of underlying empty, returns the length of a set or an array of 0, not return null.

二、HashMap、Hashtable

2.1 HashMap structure (jdk1.8)

The HashMap (array + + red-black tree list) structure, using the red-black tree, so that the chain arrays + + red-black
tree composition:

-java collection of interviews knowledge "I have heard very good use of the most complete history" Daquan
HashMap which is an array, then each array element is a singly linked list. Figure above, each of the green
entity is an instance of a nested class Entry, Entry contains four attributes: key, value, hash value, and for the next way linked list.

The 2.2 Java HashMap

The data values stored HashMap hashCode bond, may be positioned in most cases directly to its value, and thus has fast
access speed, but the traversal order is uncertain.

HashMap key allows a maximum of one record is null, allowing multiple note
is recorded null.

HashMap non-thread-safe, that is, any time you can have multiple threads simultaneously write HashMap, may result in
inconsistent data caused. If you need to meet the security thread, the method can be used synchronizedMap Collections of the
HashMap thread-safe capability, or use ConcurrentHashMap.

2.3 HashMap important parameters

  1. capacity: current array capacity 16, kept 2 ^ n, the expansion can, after expansion to the current size of the array twice.
  2. loadFactor: load factor, the default is 0.75
  3. threshold: expansion threshold, equal capacity * loadFactor

2.4 HashMap inquiry

When looking for this, according to the hash value we can quickly locate an array of
specific index, but after then, need to follow the list a comparison going to find what we need, time complexity depends
on the length of the list, is O (n) .

To reduce this overhead portion, in Java8, when the elements of the list after more than eight,
will be converted into a red-black tree list, to find the time at these positions can reduce the time complexity of O (logN).

The importance of 2.5 hashCode () and equals () method is reflected in what areas?

The use of Java HashMap hashCode () and equals () method to determine the index key value pairs, when the acquisition value based on the key when the two methods will be used. Without the correct implementation of these two methods, two different keys may have the same hash value.

Therefore, it may be considered to be equal to the set. Furthermore, these two methods can also be used to find duplicate elements. So these two methods to achieve the accuracy and correctness of the HashMap is crucial.

2.6 Hashtable

Hash table (HashTable) also known as hash table, root it to access the records by key mapped to a table in a position to accelerate the search speed. The mapping function called a hash (hash) function, recording storage array is called a hash table.

Hash table is an example of a balanced time and space. If there is no space limitations, we can directly use the key as an index of the array, so that you can find time to do the fastest (O (1)). If there are no time constraints, we can use unordered list sequential search, this requires very little memory

2.7 Why Hashtable fast speed?

Hashtable is an array of linked lists. Features of the array is easy to find, difficult to insert deleted; and the list of features is difficult to find, but easy insertion and deletion. Since both have their advantages and disadvantages, so Hashtable look easy, quick insert will delete them.

How to find 2.8 Hashtable based on key?

Use the hash function will be to find the key index into the array. Under ideal conditions, different keys may be converted to a different index values. But that is the ideal state, we practice is not always an ideal state. When a different key is generated when the same index, that is the hash collision, conflict mode:

  • Zipper law
  • Linear heuristics

2.9 LinkHashMap

LinkHashMapshi=HashMap + LinkedList

Is a collection of LinkedHashMap HashMap based implementation, having set all of the above mentioned HashMap characteristics, in addition to the characteristics HashMap disorder, LinkedHashMap is ordered, because LinkedHashMap HashMap on the basis of maintaining a separate list of all data having bidirectional the list to ensure that the order of elements iteration.

-java collection of interviews knowledge "I have heard very good use of the most complete history" Daquan

  • LinkedHashMap inherited from HashMap, HashMap and is based on a doubly linked list to achieve.
  • HashMap disorder; a LinkedHashMap order, and the intervening sequence can be divided into two kinds of access order. If you are accessing the order, when it put and get operations Entry already exists, the Entry will be moved to the end of the list doubly linked list (in fact, remove and then insert).
  • LinkedHashMap access data, or the like using the Entry HashMap [] in the way, just to ensure the doubly linked list order.
  • LinkedHashMap is not thread safe

Three, ArrayList, Vector and LinkedList

3.1 ArrayList (array)

List ArrayList is the most common implementation class, the interior is achieved through an array of elements that allows for fast random access.

Disadvantage is that the array can not be spaced between each element of the array size is not satisfied when the storage capacity needs to be increased, it is necessary to have several
replicate data set to the new storage space.

When inserting or deleting an element from the intermediate position ArrayList, it is necessary for the array into
row copy, move, the cost is relatively high. Therefore, it is suitable for random search and traversal, not suitable for insertion and deletion.

ArrayList support serialization function, support clone (shallow copy) function, sorting function

How is expansion of 3.2 ArrayList?

If no parameters configured by the words, 0 is the initial capacity of the array, when the array is actually added, really allocated capacity. Each at 1.5 times (operation position) by a ratio of expansion copeOf manner .

在 JKD6 中实现是,如果通过无参构造的话,初始数组容量为10,每次通过 copeOf 的方式扩容后容量为原来的 1.5 倍

3.3 ArrayList 集合加入 1 万条数据,应该怎么提高效率?

ArrayList 的默认初始容量为 10 ,要插入大量数据的时候需要不断扩容,而扩容是非常影响性能的。因此,现在明确了 10 万条数据了,我们可以直接在初始化的时候就设置 ArrayList 的容量!

3.4 Vector(数组实现、 线程同步)

Vector 与 ArrayList 一样,也是通过数组实现的,不同的是它支持线程的同步,即某一时刻只有一
个线程能够写 Vector,避免多线程同时写而引起的不一致性,但实现同步需要很高的花费,因此,
访问它比访问 ArrayList 慢。

3.5 LinkList(链表)

LinkedList 是用链表结构存储数据的,很适合数据的动态插入和删除,随机访问和遍历速度比较
慢。另外,他还提供了 List 接口中没有定义的方法,专门用于操作表头和表尾元素,可以当作堆
栈、队列和双向队列使用

四、HashSet、TreeSet以及LinkHashSet

Set 注重独一无二的性质,该体系集合用于存储无序(存入和取出的顺序不一定相同)元素, 值不能重复。

对象的相等性本质是对象 hashCode 值( java 是依据对象的内存地址计算出的此序号) 判断的, 如果想要让两个不同的对象视为相等的,就必须覆盖 Object 的 hashCode 方法和 equals 方法。

4.1 HashSet

哈希表边存放的是哈希值。 HashSet 存储元素的顺序并不是按照存入时的顺序(和 List 显然不同) 而是按照哈希值来存的所以取数据也是按照哈希值取得。元素的哈希值是通过元素的hashcode 方法来获取的, HashSet 首先判断两个元素的哈希值,如果哈希值一样,接着会比较equals 方法 如果 equls 结果为 true , HashSet 就视为同一个元素。如果 equals 为 false 就不是同一个元素。

HashSet 通过 hashCode 值来确定元素在内存中的位置。 一个 hashCode 位置上可以存放多个元素。

哈希值相同 equals 为 false 的元素是怎么存储呢,就是在同样的哈希值下顺延(可以认为哈希值相同的元素放在一个哈希桶中)。也就是哈希一样的存一列。 如图 1 表示 hashCode 值不相同的情况; 图 2 表示 hashCode 值相同,但 equals 不相同的情况。

-java collection of interviews knowledge "I have heard very good use of the most complete history" Daquan

4.2 TreeSet(二叉树)

  1. TreeSet()是使用二叉树的原理对新add()的对象按照指定的顺序排序(升序、降序),每增加一个对象都会进行排序,将对象插入的二叉树指定的位置。
  2. Integer 和 String 对象都可以进行默认的 TreeSet 排序,而自定义类的对象是不可以的, 自己定义的类必须实现 Comparable 接口,并且覆写相应的 compareTo()函数,才可以正常使用。
  3. 在覆写 compare()函数时,要返回相应的值才能使 TreeSet 按照一定的规则来排序
  4. 比较此对象与指定对象的顺序。如果该对象小于、等于或大于指定对象,则分别返回负整数、零或正整数

4.3 LinkHashSet( HashSet+LinkedHashMap)

对于 LinkedHashSet 而言,它继承与 HashSet、又基于 LinkedHashMap 来实现的。LinkedHashSet 底层使用 LinkedHashMap 来保存所有元素,它继承与 HashSet,其所有的方法操作上又与 HashSet 相同.

因此 LinkedHashSet的实现上非常简单,只提供了四个构造方法,并通过传递一个标识参数,调用父类的构造器,底层构造一个 LinkedHashMap 来实现,在相关操作上与父类 HashSet 的操作相同,直接调用父类 HashSet 的方法即可。

五、集合的区别

5.1 HashMap 和 Hashtable 有什么区别?

HashMap 和 Hashtable 都实现了 Map 接口,因此很多特性非常相似。但是,他们有以下不同点: HashMap 允许键和值是 null,而 Hashtable 不允许键或者值是 null。

Hashtable 是同步的,而 HashMap 不是。因此, HashMap 更适合于单线程环境,而 Hashtable 适合于多线程环境。

HashMap 提供了可供应用迭代的键的集合,因此,HashMap 是快速失败的。另一方面,Hashtable 提供了对键的列举(Enumeration)。

一般认为 Hashtable 是一个遗留的类。

5.2 数组(Array)和列表(ArrayList)有什么区别?什么时候应该使用 Array 而不是 ArrayList?

下面列出了 Array 和 ArrayList 的不同点:

Array 可以包含基本类型和对象类型,ArrayList 只能包含对象类型。

Array 大小是固定的,ArrayList 的大小是动态变化的。

ArrayList 提供了更多的方法和特性,比如:addAll(),removeAll(),iterator()等等。 对于基本类型数据,集合使用自动装箱来减少编码工作量。但是,当处理固定大小的基本数据类型的时候,这种方式相对比较慢。

5.3 ArrayList 和 LinkedList 有什么区别?

ArrayList 和 LinkedList 都实现了 List 接口,他们有以下的不同点:

ArrayList 是基于索引的数据接口,它的底层是数组。它可以以O(1)时间复杂度对元素进行随机访问。与此对应,LinkedList 是以元素列表的形式存储它的数据,每一个元素都和它的前一个和后一个元素链接在一起,在这种情况下,查找某个元素的时间复杂度是O(n)。

相对于 ArrayList,LinkedList 的插入,添加,删除操作速度更快,因为当元素被添加到集合任意位置的时候,不需要像数组那样重新计算大小或者是更新索引。

LinkedList 比 ArrayList 更占内存,因为 LinkedList 为每一个节点存储了两个引用,一个指向前一个元素,一个指向下一个元素。

也可以参考 ArrayList vs. LinkedList。

5.4 Comparable 和Comparator 接口是干什么的?列出它们的区别。

Java 提供了只包含一个 compareTo() 方法的 Comparable 接口。这个方法可以个给两个对象排序。具体来说,它返回负数,0,正数来表明输入对象小于,等于,大于已经存在的对象。

Java 提供了包含 compare() 和 equals() 两个方法的 Comparator 接口。compare() 方法用来给两个输入参数排序,返回负数,0,正数表明第一个参数是小于,等于,大于第二个参数。equals() 方法需要一个对象作为参数,它用来决定输入参数是否和 comparator 相等。只有当输入参数也是一个 comparator 并且输入参数和当前 comparator 的排序结果是相同的时候,这个方法才返回 true。

5.5 HashSet 和 TreeSet 有什么区别?

HashSet 是由一个 hash 表来实现的,因此,它的元素是无序的。add(),remove(),contains()方法的时间复杂度是 O(1)。

另一方面,TreeSet 是由一个树形的结构来实现的,它里面的元素是有序的。因此,add(),remove(),contains() 方法的时间复杂度是 O(logn)。

5.6 HashMap 和 ConcurrentHashMap 的区别?

ConcurrentHashMap 是线程安全的 HashMap 的实现。主要区别如下:

  1. ConcurrentHashMap 对整个桶数组进行了分割分段(Segment),然后在每一个分段上都用 lock 锁进行保护,相对 于Hashtable 的 syn 关键字锁的粒度更精细了一些,并发性能更好。而 HashMap 没有锁机制,不是线程安全的。

  2. HashMap 的键值对允许有 null ,但是 ConCurrentHashMap 都不允许

JDK8 之后,ConcurrentHashMap 启用了一种全新的方式实现,利用 CAS 算法。

5.7 List、Set、Map 是否继承自 Collection 接口?

List、Set 是,Map 不是。Map 是键值对映射容器,与 List 和 Set 有明显的区别,而 Set 存储的零散的元素且不允许有重复元素(数学中的集合也是如此),List 是线性结构的容器,适用于按数值索引访问元素的情形。

5.8 说出 ArrayList、Vector、LinkedList 的存储性能和特性?

ArrayList 和 Vector 都是使用数组方式存储数据,此数组元素数大于实际存储的数据以便增加和插入元素,它们都允许直接按序号索引娶元素,但是插入元素要涉及数组元素移动等内存操作,所以索引数据快而插入数据慢,Vector 由于使用了 synchronized 方法(线程安全),通常性能上较 ArrayList 差。

And LinkedList implemented using a doubly linked list is stored (in the memory by the associated reference memory cell scattered added together to form a linear structure can be indexed by serial number, which compared to a continuous chain storage array storage, in fact memory higher utilization), indexed by serial number data needs to be prior to or after the traverse, but the only record of this term to insert the data before and after, the insertion speed.

Vector belong legacy container (container earlier JDK used, in addition to Hashtable, Dictionary, BitSet, Stack, Properties are the legacy container), is now not recommended, but due to the ArrayList and LinkedListed are not thread-safe, if operating a plurality of threads requires the same container, the method can synchronizedList Collections of tools to convert it into thread-safe container before use (this is actually the best mode example of decoration, the object will have passed another class the constructor to create a new object to add new features).

5.9 List, when the Map, Set three interfaces storage elements What are the characteristics?

  • List is ordered Collection, use this interface to accurately control the position of insertion of each element. Users can use index (List elements in the position, similar to the array subscript) to access elements in the List, which is similar to an array of Java.
  • Set does not contain a repeat element Collection, i.e., any two elements e1 and e2 are e1.equals (e2) = false, Set up to a null element.
  • Map interface: Please note, Map Collection interfaces do not inherit, Map provides the mapping key to value

Welcome attention to micro-channel public number [ Ccww notes ], original technical articles first time launch.

-java collection of interviews knowledge "I have heard very good use of the most complete history" Daquan

Guess you like

Origin blog.51cto.com/11046499/2454340