[Java container source code series] Comparison of collection classes in jdk8 and jdk7

1. List difference

1.1 ArrayList (small changes)

When ArrayList is initialized without parameters, Java 7 directly initializes the size of 10. Java 8 removes this logic. It is an empty array during initialization. It starts to expand according to 10 when the first add is added. The following figure shows the difference comparison chart of the source code:

Java 7 and 8 have not changed in other aspects of List.

2.Map difference

2.1 HashMap (large changes)

  1. Like ArrayList, HashMap in Java 8 discards the direct array initialization 16 in Java 7 in the no-parameter constructor, but uses the first time it is added to expand the array size;
  2. The hash algorithm calculation formula is different. The hash algorithm of Java 8 is simpler and the code is more concise;
  3. Java 8's HashMap adds a red-black tree data structure, which is not available in Java 7. Java 7 only has an array + linked list structure. Java 8 proposes an array + linked list + red-black tree structure. Generally, the key is Java. When using APIs, for example, String hashcodes implement good APIs, and it is rare that linked lists are converted into red-black trees. Because the hash algorithms of String APIs are good enough, only when the key is our custom class, and we override When the hashcode algorithm written is very bad, red-black trees will be used to improve our retrieval speed.
  4. It is also because Java 8 has added red-black trees, so almost all the methods of operating arrays have been changed, such as put, remove and other operations. It can be said that the HashMap of Java 8 is almost rewritten again, so the Java 7 Many problems have been solved by Java 8, such as a very small probability of deadlock during expansion, loss of data and so on.
  5. Added some useful methods,
    • For example, getOrDefault, we look at the source code, it is very simple:
    // 如果 key 对应的值不存在,返回期望的默认值 defaultValue
    public V getOrDefault(Object key, V defaultValue) {
          
          
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
    }
    
    1. There is also putIfAbsent(K key, V value) method, which means that if there is a key in the map, then the value will not be overwritten. If there is no key, the addition is successful.
    2. There is also a compute method, which means that we can calculate the values ​​of key and value and then put them into the map. To prevent unknown errors caused by the absence of the key value, the map also provides the computeIfPresent method, which means that only when the key exists, The calculation is performed, the demo is as follows:
@Test
  public void compute(){
    
    
    HashMap<Integer,Integer> map = Maps.newHashMap();
    map.put(10,10);
    log.info("compute 之前值为:{}",map.get(10));
    map.compute(10,(key,value) -> key * value);
    log.info("compute 之后值为:{}",map.get(10));
    // 还原测试值
    map.put(10,10);

    // 如果为 11 的 key 不存在的话,需要注意 value 为空的情况,下面这行代码就会报空指针
    //  map.compute(11,(key,value) -> key * value);
    
    // 为了防止 key 不存在时导致的未知异常,我们一般有两种办法
    // 1:自己判断空指针
    map.compute(11,(key,value) -> null == value ? null : key * value);
    // 2:computeIfPresent 方法里面判断
    map.computeIfPresent(11,(key,value) -> key * value);
    log.info("computeIfPresent 之后值为:{}",map.get(11));
  }

The results are:

compute 之前值为:10
compute 之后值为:100
computeIfPresent 之后值为:null(这个结果中,可以看出,使用 computeIfPresent 避免了空指针)

2.2 LinkedHashMap

Due to changes in the underlying data of Java 8, the method of HashMap manipulation of data is almost rewritten, and the implementation name of LinkedHashMap is different. The principle is the same. Let’s look at the figure below, the left is Java 7 and the right is Java 8. .

From the figure, we find that the method name of LinkedHashMap has been modified, and the underlying implementation logic is actually the same.

3. Other differences

Arrays provides many methods at the beginning of parallel.

Java 8's Arrays provides some methods starting with parallel. These methods support parallel calculations. When the amount of data is large, the CPU will be fully utilized to improve calculation efficiency. For example, the parallelSort method has a judgment at the bottom of the method, only the amount of data is greater than 8192. In actual experiments, parallel computing can indeed rapidly increase the computing speed.

4. Several questions

  1. Java 8 has added many new methods to the List and Map interfaces. Why don't implementers of these interfaces in Java 7 need to implement these methods?
    Answer: The main reason is that these new methods are modified by the default keyword. Once the default method is modified on the interface, we need to write the default implementation in the method of the interface, and the subclass does not need to implement these methods, so the Java 7 interface The implementer does not need to perceive.

  2. There are many new practical methods in Java 8. What are they?
    Answer: For example, getOrDefault, putIfAbsent, computeIfPresent methods, etc. Please refer to the above for specific usage details.

  3. Talk about the posture of the computeIfPresent method?
    Answer: computeIfPresent can calculate the key and value, and then re-assign the result of the calculation to the key. If the key does not exist, it will not report a null pointer and return a null value.

  4. The forEach method is added to the Java 8 collection. How is it different from the normal for loop?
    Answer: The input parameters of the new forEach method are functional interfaces, such as Consumer and BiConsumer. The advantage of doing this is that the code of the for loop is encapsulated, so that users only need to pay attention to the business logic of each loop, simplifying The repeated for loop code makes the code more concise. For ordinary for loops, you need to write repeated for loop codes every time. ForEach eats up this repeated calculation logic and makes it more convenient to use.

  5. What is the difference between HashMap 8 and 7?
    Answer: The difference between HashMap 8 and HashMap 7 is too great. Red-black trees have been added, the underlying data logic has been modified, and the hash algorithm has been modified. Almost all the methods for changing the underlying array have been rewritten. It can be said that Java 8 HashMap is almost Do it again.

Guess you like

Origin blog.csdn.net/weixin_43935927/article/details/108532891