Java collection summary [interview questions + brain map], to catch all the knowledge points!

foreword

Statement, this article uses jdk1.8

It took a week to go through the core knowledge of Java containers , and I feel that collections have no fear! ! (Hahaha....), let's summarize now~~

Review the table of contents:

Java containers can be divided into two categories:

  • Collection
    • List
      • ArrayList
      • LinkedList
      • Vector (understand, obsolete)
    • Set
      • HashSet
        • LinkedHashSet
      • TreeSet
  • Map
    • HashMap
      • LinkedHashMap
    • TreeMap
    • ConcurrentHashMap
    • Hashtable (understand, obsolete)

The ones highlighted are the ones we use the most .

In fact, I don't know how to summarize it, because I have summarized it when I wrote each article before. It seems a little watery to list them all again now, so I decided to answer some Java container interview questions!

Of course, my answer may not be correct. If there are any mistakes, please include them a lot, and I hope you will not hesitate to leave a message in the comment area to correct them~~

First, the difference between ArrayList and Vector

Common ground:

  • Both of these classes implement the List interface, they are both ordered collections (stored in order), and the bottom layer is an array . We can fetch an element by its position index, allowing elements to be repeated and null .

the difference:

  • Synchronization:
    • ArrayList is asynchronous
    • Vector is synchronous
    • Even when synchronization is required, we can use the Collections utility class to build a synchronized ArrayList instead of Vector
  • Expansion size:
    • Vector doubles the original size, ArrayList grows 0.5 times the original size

Second, the difference between HashMap and Hashtable

Common ground:

  • In terms of storage structure and implementation, they are basically the same, and they all implement the Map interface~

the difference:

  • Synchronization:
  • Whether to allow null:
    • HashMap allows null
    • Hashtable does not allow null
  • contains method
    • This knowledge point was brushed on Niuke.com. I didn't expect this kind of question to exist (I don't like it very much). …
    • Hashtable has contains method
    • HashMap removed the contains method of Hashtable and changed it to containsValue and containsKey
  • Inheritance is different:
    • HashMap<K,V> extends AbstractMap<K,V>
    • public class Hashtable<K,V> extends Dictionary<K,V>

3. The difference between List and Map

Common ground:

  • They are all commonly used containers in Java, and they are all interfaces (ps: writing it feels like it is the same as not writing it...)

difference:

  • The storage structure is different :
    • List is a collection that stores a single column
    • Map stores a collection of key-value key-value pairs
  • Is the element repeatable :
    • List allows elements to be repeated
    • Map does not allow duplicate keys
  • Is it in order :
    • List collection is ordered (stored in order)
    • Map collection is unordered (storage is unordered)

Fourth, the elements in the Set cannot be repeated, so what method is used to distinguish whether it is repeated or not? Is it to use == or equals()?

We know that the Set collection actually mostly uses the put method of the Map collection to add elements .

Taking HashSet as an example, the elements in HashSet cannot be repeated, which is reflected in the source code (HashMap) as follows:

	
	// 1. 如果key 相等  
    if (p.hash == hash &&
        ((k = p.key) == key || (key != null && key.equals(k))))
        e = p;
	// 2. 修改对应的value
	   if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
       }

When adding elements, if the key (also the corresponding element of the Set collection) is equal, then modify the value. In the Set collection, the value value is just an Object object ( the object is useless to the Set itself ).

That is to say: if the added elements of the Set collection are the same, it is not inserted at all (only a useless value is modified) ! It can also be seen from the source code (HashMap) that both == and equals() methods are used !

Five, the difference between Collection and Collections

  1. Collection is the upper-level interface of collection , and it inherits from Set and List interfaces
  2. Collections is a tool class for collections , which provides a series of static methods to search, find, synchronize and other operations on collections

Six, say the storage performance and characteristics of ArrayList, LinkedList

The bottom layer of ArrayList is an array, and the bottom layer of LinkedList is a doubly linked list.

  • ArrayList supports indexing the corresponding elements by the position of the corner index (random access), while LinkedList needs to traverse the entire linked list to obtain the corresponding elements. Therefore , in general, the access speed of ArrayList is faster than that of LinkedList.
  • Because ArrayList is an array, the consumption for deletion and modification is relatively large (implemented by copying and moving arrays). LinkedList is a doubly linked list. Deletion and modification only need to modify the corresponding pointer, and the consumption is very small. Therefore , in general, the addition and deletion speed of LinkedList is faster than that of ArrayList.

6.1 Extensions:

The addition and deletion of ArrayList is not necessarily slower than LinkedList.

  • If additions and deletions are performed at the end [remove() and add() are called each time], then ArrayList does not need to move and copy the array to operate. If the amount of data is in the millions, the speed will be faster than LinkedList . (I tested)
  • If the position of the delete operation is in the middle . Since the consumption of LinkedList is mainly in traversal, the consumption of ArrayList is mainly in moving and copying (the bottom layer calls the arraycopy() method, which is the native method).
    • The traversal speed of LinkedList is slower than the copy movement speed of ArrayList
    • If the amount of data is in the millions, ArrayList is still faster . (I tested)

Seven, the difference between Enumeration and Iterator interfaces

I didn't talk about them in detail in the previous article, but I just know that: Iterator replaces Enumeration, and Enumeration is an old iterator.

Compared to Enumeration, Iterator is safer because it prevents other threads from modifying the collection while it is being traversed .

  • When we are doing exercises, will there be frequent errors during iteration, throwing ConcurrentModificationException exceptions, saying that we are still modifying elements while traversing.
  • This is actually the fail-fast mechanism~ For details, please refer to the blog post: blog.csdn.net/panweiwei19…

There are three differences:

  • The method name of Iterator is more scientific than Enumeration
  • Iterator has a fail-fast mechanism, which is more secure than Enumeration
  • Iterator can delete elements, Enumeration can not delete elements

Eight, what are the characteristics of ListIterator

  • ListIterator inherits the Iterator interface, which is used to traverse the elements of the List collection .
  • ListIterator can implement bidirectional traversal, add elements, set elements

Take a look at the source code method to know:

 

 

9. What is the concurrent collection class?

The Java 1.5 concurrency package (java.util.concurrent) contains thread-safe collection classes that allow the collection to be modified while iterating .

  • Iterators are designed to be fail-fast and throw ConcurrentModificationException.
  • Some of the classes are:
    • CopyOnWriteArrayList
    • ConcurrentHashMap
    • CopyOnWriteArraySet

10. If the key value of HashMap in Java is a class object, what conditions does the class need to meet?

You need to override both the hashCode() method of this class and its equals() method .

  • It can be known from the source code that when inserting an element, the hashCode of the object is calculated first . If the hashcode is equal. Then it indicates that the object is stored in the same location.
  • If the equals() method is called and the two keys are the same , the element is replaced
  • If the equals() method is called and the two keys are different , it means that the hashCode just happens to be the same . At this time, it is a hash conflict, and the newly added element is placed on the bucket.

Generally speaking, we will think: as long as the values ​​of the member variables of two objects are equal, then we consider these two objects to be equal ! Because the bottom layer of Object compares the addresses of two objects, and this does not make much sense for our development~ That's why we have to rewrite the equals()method

If you override the equals() method, you must override the hashCode() method. Because equals() determines that these two objects are the same , and when the same object calls the hashCode() method , it should return the same value!

11. What are the best practices related to the Java Collections Framework

  1. Determine the type of collection as needed . If it is a single-column collection, we consider using the subinterfaces ArrayList and Set under Collection. If it is a map, we consider using Map~
  2. After determining our collection type, we next determine which subclass under the collection type to use ~ I think it can be simply divided into several steps:
    • Does it need to be synchronized
      • Find a thread-safe collection class to use
    • Does it need to be ordered when iterating (insertion order is ordered)
      • Find the Linked two-way list structure
    • Whether sorting is required (natural order or manual sorting)
      • Go to the Tree red-black tree type (JDK1.8)
  3. Estimating the amount of data stored in the collection, whether it is a List or a Map, they achieve dynamic growth, which all have performance consumption. Giving a reasonable capacity in the initial collection will reduce the consumption of dynamic growth~
  4. Use generics to avoid ClassCastException at runtime
  5. Use the Collections utility class whenever possible, or get a read-only, synchronized, or empty collection instead of writing your own implementation . It will provide code reuse, it has better stability and maintainability

12. How to improve efficiency when adding 10,000 pieces of data to ArrayList collection

The default initial capacity of ArrayList is 10. When a large amount of data needs to be inserted, the capacity needs to be continuously expanded, and the capacity expansion will greatly affect the performance. Therefore, now that 100,000 pieces of data are clarified, we can directly set the capacity of the ArrayList during initialization !

This will improve the efficiency~

13. Summary

At 17:14:03 on April 15, 2018, I found some interview questions and answered them, but I felt that it was not enough. I haven't found the corresponding interview questions for many knowledge points that I think are more important (maybe my search ability is too watery?).

I took this article as a summary of the collection, but I felt that there was nothing to write, so I went to answer some interview questions. After looking for the interview questions for a while, I felt that it was not systematic enough. And this summary I do not want to copy the summary of the previous chapters here. So I decided to draw a mind map to end this post !

April 15, 2018 19:31:33 Finished drawing! ! ! ! !

 

 

Students who need more brain maps can pay attention to the public number: Java3y, just reply to [brain map]~

If there are any mistakes in the article, please correct me, and we can communicate with each other. Students who are used to reading technical articles on WeChat and want to get more Java resources can follow WeChat public account: Java3y . Thank you for your support! Hope to introduce more to other friends in need

Article directory navigation : zhongfucheng.bitcron.com/post/shou-j…

At present, I plan to write multi-threading. What do you think ? You can leave a message in the comment area~


 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324406380&siteId=291194637