Follow me for more interesting interview questions. This article is included in “Offer to the Bowl” — Java Basics

Written in the book before

Hello, everyone, for a long time no updated article, when a long time of salty fish ~~~~

In the last article, I shared with you how difficult it was to find an internship during the school recruitment. The general writing was relatively simple. Today, I would like to share with you some interview questions when preparing for the interview. Also read a lot of classic books (such as “Java programming ideas”, “In-depth understanding of Java Virtual Machine”, “Java concurrent programming art”, etc.), summed up some knowledge points, share with everyone to share, and review some knowledge points.

The main theme of this article is “Java basic related to the interview questions”, the structure of the explanation is mainly the topic + answer expansion, we can first look at the topic, then look at the answer, it is not recommended to recite the answer directly.

Twelve core questions

1. The difference between String, StringBuilder and StringBuffer

The similarities and differences between these three string classes are mainly concerned with mutable and immutable, and security and insecurity:

  1. StringBuffer(simultaneous) andString(immutable) are thread-safe,StringBuilderIs thread unsafe;
  2. StringIs immutable,StringBuilderandStringBufferIs mutable;
  3. StringThe underlying connection operation is made byStringBuilderThe implementation;
  4. All three arefinalIs not allowed to be inherited;
  5. StringBuilderAs well asStringBufferThese are abstract classesAbstractStringBuilderSubclasses of, their interfaces are the same.

Why is String immutable?

  1. StringThe three main member variablesChar value[], int offset, int countAll isPrivate, finalAnd there is no correspondinggetter/setter;
  2. StringOnce the object is initialized, the above three member variables cannot be modified. And any modifications to these fields by the interface they provide will return a new object;

2. Reload

  1. Overloading: in-class polymorphism, static binding (which method is executed is known at compile time), methods with the same name and different parameters
  2. Rewrite: inter-class polymorphism, dynamic binding mechanism (determined at run time), instance methods, two small, two big principle.

The method signatures are the same, and the range of exceptions and return values thrown by methods of subclasses is no greater than that of corresponding methods of the parent class, and the visibility of methods of subclasses is no less than that of corresponding methods of the parent class

3. Abstraction, encapsulation, inheritance, polymorphism

The four main features of Java are summarized as follows:

  1. Encapsulation: Encapsulate the attributes and behaviors (data) of an object into an independent whole, and hide the internal implementation details of the object as much as possible;
  2. Inheritance: a code reuse mechanism;
  3. Polymorphism: Separating the what from the how, separating the interface from the implementation from another perspective, eliminating the coupling between types; Representation: overloading and overwriting; On polymorphism, rhubarb wrote a humble article on What Polymorphism is.
  4. 3. Another expression for inheritance; Representation: Interfaces (contracts) and abstract classes (templates)

4. ArrayList vs. LinkedList

1. ArrayList has the following features:

  1. The default initial capacity is 10
  2. Expansion mechanism: Before adding an element, check whether the element needs to be expanded. Generally, the element needs to be expanded to 1.5 times of the source array + 1
  3. Boundary checking (i.eArrayListSize) : Refers toindexThe operation;
  4. Resize the array (reducing the size) : Resize the underlying array to the size of the actual elements held in the current list.
  5. In the search for a given element index value method, the source will be the element value is null and not null two cases;

ArrayList: ArrayList: ArrayList: ArrayList: ArrayList: ArrayList

2, LinkedList core point LinkedList not only implements the List interface, but also implements the Dequeue interface. Thus, LinkedList can be used not only as a List, but also as a Stack(push, POP, peek) and Queue(offer, poll, peek).

ArrayList and LinkedList

  1. ArrayListIs an array-based implementation,LinkedListThe realization of bidirectional cyclic linked list based on lead node;
  2. ArrayListSupport random access,LinkedListDoes not support;
  3. LinkedListCan be used as a queue and stack, achievedDequeueInterface, andArrayListNo;
  4. ArrayList Addressing efficiency is high, insert/delete efficiency is low;LinkedListInsert/delete efficiency is high, addressing efficiency is low

5. Fail Fast mechanism of containers

Fail-fast is an error-detection mechanism for Java collections that prevents other threads from structurally modifying a Collection while one thread iterates over it. In the face of concurrent modifications, the iterator will soon complete failure, rather than risking some uncertainty in the future time the risk of any uncertain behavior, throw ConcurrentModificationException.

private class Itr implements Iterator<E> {  
    int cursor;  
    int lastRet = -1;  
    int expectedModCount = ArrayList.this.modCount;  

    public boolean hasNext(a) {  
        return (this.cursor ! = ArrayList.this.size);  
    }  

    public E next(a) {  
        checkForComodification();  
        /** omit this code */  
    }  

    public void remove(a) {  
        if (this.lastRet < 0)  
            throw new IllegalStateException();  
        checkForComodification();  
        /** omit this code */  
    }  

    final void checkForComodification(a) {  
        if (ArrayList.this.modCount == this.expectedModCount)  
            return;  
        throw newConcurrentModificationException(); }}Copy the code

6. Set (HashSet, LinkedHashSet, TreeSet) different implementation classes

The biggest thing about a Set, and the main reason for using it, is that it contains no duplicate elements. Common Set implementations are HashSet, LinkedHashSet, and TreeSet. In general, if you need a fast access Set, you should use HashSet; When you need a sorted Set, you should use TreeSet; You should use LinedHashSet when you need to record the order of insertion.

1, HashSet: the underlying implementation through HashMap, to achieve the Set interface.

A HashSet is implemented using a hash table, in which the elements are not arranged in order. Methods like add(), remove(), and contains() are all O(1) complexity methods. By observing the underlying code, it is found that the underlying HashSet is basically implemented through HashMap

Five constructors = 4(implementation based on HashMap for implementation of HashSet) + 1(implementation based on LinkedHashMap for implementation of LinkedHashSet)

2, LinkedHashSet: is a subclass of HashSet, the bottom class is mainly implemented by the subclass of HashMap LinkedHashMap, to achieve the Set interface

LinkedHashSet descends from HashSet, using the HashSet constructor below. Note that this is the package access that is specifically called by the LinkedHashSet constructor. LinkedHashSet, intermediate in performance between HashSet and TreeSet, is a subclass of HashSet and a hash table, but also maintains a double-linked list to record the order of inserts. The basic method complexity is O(1).

3. TreeSet: The bottom layer is mainly implemented by TreeMap.

TreeSet is implemented in a tree structure (red-black tree algorithm). Elements are arranged in order, but methods like add(), remove(), and contains() are all O(log (n)) complexity methods. TreeSet also provides some methods to handle sorted sets. First, last, headSet, tailSet, etc. Also, unlike HashSets and Linkedhashsets, TreeSet must store elements that are sortable (elements implement the Comparable interface or pass in a Comparator) and cannot hold null values.

7. Map and three common implementations of Map

List the arrayHashMap.LinkedHashMap(HashMapSubclass, bidirectional linked list of the leading node +HashMap), based on red black treesTreeMap(sort key)]

The Java 8 Series reintroduces HashMap

8. How to determine whether two objects in a container are equal

  1. Determine whether the hashcodes of two objects are equal: if they are not, the two objects are not equal either; If they are equal, go to step 2;

  2. Determine whether two objects are equal using equals: if they are not equal, they are considered not equal. If equal, two objects are considered equal

9. ConcurrentHashMap, HashMap, and HashTableThe difference between

  1. ConcurrentHashMap and HashMap are AbstractMap subclasses, and HashTable is Dictionary subclass.

  2. Thread-safe: HashMap is thread-safe, while ConcurrentHashMap and HashTable are thread-safe, but their thread-safe policies are different. The former adopts the piecewise lock mechanism. By default, it can support concurrent write of 16 threads and concurrent read of any thread, with high efficiency. HashTable uses synchronous operations, which are inefficient

  3. Key-value constraints: A HashMap allows null keys and values, but ConcurrentHashMap and HashTable do not allow null keys or values.

  4. Hash strategy: The three hash strategies are different, HashTable is the key. HashCode mod; ConcurrentHashMap and HashMap hash hashCode first and then mod (buckets -1), but their hash algorithms are different.

  5. Expansion mechanism: The expansion check mechanisms are different. ConcurrentHashMap and HashTable are checked before elements are inserted, and HashMap is checked after elements are inserted.

  6. Initial capacity: Initial capacity of HashTable 11, double capacity + 1; The initial capacity of HashMap is 16. Expand the capacity by 2 times

10. Equals, hashCode, == difference

Rhubarb has explained the differences between the three in detail in his previous article.

1. In summary, there are the following points:

  1. = =Used to determine whether two objects are the same object or whether the values of two basic types are equal;
  2. equalsUsed to determine whether two objects have the same content;
  3. hashCodeIs of an objectMessage digest function, a kind ofCompression mapping, its general andequals()Method overridden simultaneously; If you don’t rewrite thehashCodeMethod, used by defaultObjectOf the classhashCodeMethod, which is a local method created byObjectThe class definitionhashCodeMethod returns different integers for different objects.

2, the collection uses mutable objects asKeyProblems brought about

A HashMap uses Key hashes to store and find key-value pairs. If the hash of a HashMap Key changes after storing key-value pairs, the Map may no longer find the Entry. That is, mutable objects as keys in a HashMap cause data loss. Therefore, the following suggestions are generally made:

  1. inHashMapUse immutable objects as far as possibleKeyFor example, useStringSuch immutable types are used asKeyIt is wise to use your own immutable classes.
  2. If the mutable object is inHashMapBe careful not to change the hash value of an object when changing its state, for example, from only the object’s identity attributeHashCode.

Overwrite equals but not HashCode

If you add two identical objects to a Set (equals returns true), the hashCode values of the two objects must be different because the hashCode function has not been overridden, and they are likely to be split into different buckets, resulting in duplicate objects.

11. What is immutable

An immutable object should satisfy the following conditions:

  1. The value of a primitive type variable is immutable;
  2. Reference type variables cannot point to other objects;
  3. The state of the object to which the reference type refers is immutable;
  4. Besides constructors, no other functions (at least any public functions) should modify any member variables;
  5. Any function that acquires a new value for a member variable should store the new value in the new object, leaving the original object unmodified.

12. Java serialization/deserialization mechanism

The Serializable interface can be converted to a sequence of bytes with Serializable serialization/deserialization, and can be fully restored to the original object in the future. Serialization can compensate for differences between different operating systems.

Serialization specific meaning:

  1. Objects that need to be serialized must be implementedSerializableInterface;
  2. There are only non-static fields and nottransientThe field is serialized, regardless of the visibility of the field;

conclusion

The Offer quickly into a bowl to interview preparation – Java foundation papers to 01 here over, twelve points mentioned here is just a handful of the Java knowledge, is selected from the preparation before autumn recruit, avoid to the world of interview questions collection, subsequent have any questions or anything want to know can direct messages to me, I will also gradually improve the Offer to the bowl series.