preface

Welcome to our GitHub repository Star: github.com/bin39232820… The best time to plant a tree was ten years ago, followed by now

Tips

The interview guide series, which in many cases does not delve into the details, is a way for students to review their knowledge in the role of the interviewee, so I assume that most of the things you, as the interviewer, know.

www.processon.com/view/link/6…

This is the brain map address

Where t

You might think it’s a cliche, and it is. Interview questions, interview treasure book, just a search, you can’t finish reading, also can’t come over, then I write this meaning and what? Actually, I wrote this for the following purposes

  • The first is through a system of review, so that their own front to write the article again over, summary sublimation
  • The second is to help you establish a review system by writing articles. I will make an introduction to most of the knowledge points that will be asked in the form of point by point

Then below is a summary of previous articles

  • 2021-Java Backend Engineer Interview Guide (Introduction)

Finally, review all knowledge points in the form of interview questions, and sort out some more common interview questions and problems encountered in their actual development.

Java basics

What is the difference between Java character constants and string constants?

In the development process, we should use more strings, so to be familiar with the character constants, we can answer

  • Formal: A character constant is a character enclosed by a single quotation mark; String constants are zero or more characters enclosed by double quotes
  • A character constant is equivalent to an integer value (ASCII value) and can participate in expression operations. A string constant represents an address value (where the string is stored in memory)
  • Memory size character constants are only 2 bytes; String constants take up several bytes

What’s the difference between String and StringBuilder?

  • The Java platform provides two types of String: a String and StringBuffer/StringBuilder, they can store and manipulate strings.
  • String is read-only, which means that the contents of the String referenced by String cannot be changed.
  • The StringBuffer/StringBuilder class says string objects can be modified directly. StringBuilder, introduced in Java 5, is exactly the same method as StringBuffer, except that it is used in a single-threaded environment because none of its aspects are modified by synchronized, It is also more efficient than StringBuffer.

Small talkative, is also in telling myself, in fact, I believe the answer to the questions most people’s will, also back the place, but we really do not abide by in the process of development, sometimes we are dealing with some logic, for example, when we will get used to the need to splice some field with +, do not know to have the same development. Ha ha, small 66 and everyone try to develop good development habits

Talk about the use and implementation of reflection

Java reflection mechanism is a very powerful function, in many projects such as Spring, MyBatis can see reflection figure. With reflection, we can get the type information of an object at run time. This allows us to implement design patterns such as factory and proxy patterns, as well as solve vexing problems such as Java generic erasure.

Get the reflection class of an object. In Java, there are the following methods to get the reflection class of an object

  • New an object, and then the object.getClass () method
  • Through the class.forname () method
  • Use class. The class

Say if there are any BigDecimal pits encountered, or points to watch out for

  • When we use BigDecimal, we recommend using its BigDecimal(String) constructor to create objects in order to prevent loss of precision.

It’s just to see if our actual development is paying attention to these points,

Tell me how you normally turn a comma-separated string into a set, something like (“1,2,3”)

  • List myList = arrays.stream (myArray).collect(Collectors. ToList ()). This method is recommended instead of List myList = arrays.aslist (1, 2, 3).
  • The reason is that arrays.aslist () converts an array to a collection, but it’s still an array

String s=new String(” ABC “);

  • I’m sure you’re familiar with this problem, and the answers are well known, one or two.
  • Start by creating a specified object “ABC” in the heap (not the constant pool) and having STR references point to that object
  • Check for “ABC” string objects in the string constant pool
  • If so, associate the string object from new with the object in the string constant pool
  • If not, create a string object with the content “ABC” in the string constant pool and associate the objects in the heap with it

Talk about SPI in Java

Each abstraction of system design, there are often many different implementation schemes. In object-oriented design, it is generally recommended to program based on interface between modules, not hard coding between modules. Once a specific implementation class is involved in the code, it violates the principle of pluggability, and if an implementation needs to be replaced, the code needs to be changed. A service discovery mechanism is needed in order to realize the dynamic specification during module assembly. The Java SPI provides a mechanism for finding a service implementation for an interface. Similar to the IOC idea of moving control of assembly out of the program, this mechanism is especially important in modular design. So the core idea of SPI is decoupling.

Talk about the features of Java 8

  • Functional interface
  • Interfaces can have implementation methods and do not need implementation classes to implement their methods.
  • Lambda expressions
  • The stream flow
  • Datetime API LocalDateTime year month day ten minutes seconds; LocalDate date; The LocalTime time
  • Optional class

Although the latest version is already 15, most enterprises still use 8, so let’s talk about this.

What is the difference between a member variable and a local variable?

  • Member variables can be modified by modifiers such as public,private, and static, while local variables cannot be modified by access-control modifiers or static. However, both member variables and local variables can be modified by final.
  • If a variable is static, it belongs to the class. If it is not static, it belongs to the instance. Objects live in heap memory and local variables live in stack memory
  • From the variable in memory survival time: the member variable is a part of the object, it exists with the creation of the object, and the local variable with the method call and automatically disappear.
  • If a member variable is not assigned an initial value: it is automatically assigned to the default value of the type (except for the case that final modified member variables must also be explicitly assigned), while local variables are not automatically assigned.

What are the properties of constructors?

  • Name is the same as the class name.
  • There is no return value, but a constructor cannot be declared with void.
  • Automatically executed when an object of the class is generated, no call required.

Talk about equals == and equals

  • == : This is used to determine whether the addresses of two objects are equal. That is, determine whether two objects are the same object (base data type == compares values, reference data type == compares memory addresses).
  • Equals () : Also checks whether two objects are equal. But it is generally used in two ways:
    • Case 1: The class does not override equals(). Comparing two objects of that class through equals() is equivalent to comparing them through “==”.
    • Case 2: The class overrides equals(). In general, we override the equals() method to compare the contents of two objects; Return true if their contents are equal (that is, the objects are considered equal).

Let’s talk about four Java references, weak and weak

Small six six side said, in fact, we as a CRUD, usually the real contact may be strong citation, but it is not to say that other citation is useless, there is reasonable, we have a look at their specific role! It feels like it should be in the JVM module, but I’ll leave it there

  • Strong references: The most common type of reference, such as String s = “ABC”, where the variable s is a strong reference to the String “ABC”. As long as the strong reference exists, the garbage collector will not reclaim the object.
  • Soft reference: Used to describe objects that are useful but not necessary and not recycled if there is enough memory, or recycled if there is not. Commonly used for memory-sensitive caching (when customizing memory cached), soft references can be used in conjunction with the ReferenceQueue ReferenceQueue, and if the soft reference object is garbage collected, the JVM adds the soft reference to the ReferenceQueue associated with it.
  • Weak references: Weak references and soft references are roughly the same. The difference between weak and soft references is that objects with only weak references have a shorter lifetime. When the garbage collector thread scans the memory area under its control, once it finds an object with only weak references, it reclaims its memory regardless of whether the current memory space is sufficient. (This is garbage.)
  • Virtual references: Virtual references do not change the life cycle of an object; if an object holds only virtual references, it is as good as no references at all. (In case we forget to remove, ThreadLocal is the only way we understand virtual references.)

Java container Collection

Let’s talk about arrays

  • Consistency: Arrays can only hold elements of the same data type, and the data type of the elements can be any of the same data type.
  • Orderliness: Elements in an array are ordered and accessed by subscripts.
  • Immutability: Once an array is initialized, its length (the number of elements in the array) is immutable. An array is a linear structure of continuous storage with the same element type and equal size

Talk about common Java collections

Well, I think we’re going to ask this a lot, kind of an introduction to set testing

  • The Map and Collection interfaces are the parent interfaces of all collections frameworks
  • The subinterfaces of the Collection interface include Set interface and List interface
  • The Map interface implementation classes include HashMap, TreeMap, Hashtable, ConcurrentHashMap, and Properties
  • The main implementation classes of Set interface are: HashSet, TreeSet, LinkedHashSet and so on
  • List interface implementation classes are: ArrayList, LinkedList, Stack and Vector, etc

Let’s talk about the differences between sets, lists, and maps

List

  • Duplicate objects can be allowed.
  • Multiple NULL elements can be inserted.
  • Is an ordered container that maintains the insertion order of each element, and the output order is the insertion order.

Set

  • Duplicate objects are not allowed
  • Unordered containers. You can’t guarantee the order in which each element is stored. TreeSet maintains a sort order using Comparator or Comparable.
  • Only one NULL element is allowed

Map

  • Map is not a subinterface or implementation class of Collection. Map is an interface.
  • Each Entry of a Map holds two objects, one key and one value. The Map may hold the same value object, but the key object must be unique.
  • You can have any number of NULL values in a Map but you can only have one null key at most.

Their usage scenarios

  • If you often use indexes to access elements in containers, then List is the right choice for you. List implementation classes such as ArrayList can provide faster access if you already know about indexes, and if you frequently add and delete elements, definitely choose LinkedList.
  • If you want elements in a container to be ordered in the order in which they were inserted, then List, because List is an ordered container, it’s stored in the order in which it was inserted.
  • If you want to ensure that the inserted elements are unique, that is, you don’t want duplicate values, then choose a Set implementation class such as HashSet, LinkedHashSet, or TreeSet. All Set implementation classes follow uniform constraints such as uniqueness, but also provide additional features such as TreeSet being a SortedSet, All elements stored in TreeSet can be sorted using the Java Comparator or Comparable. LinkedHashSet also stores elements in the order in which they were inserted.
  • If you store data in the form of keys and values, Map is the right choice. You can choose from Hashtable, HashMap, or TreeMap depending on your subsequent needs. `

Let’s talk about the difference between ArrayList and LinkedList

  • ArrayList is a data structure based on dynamic arrays, and LinkedList is a data structure based on linked lists.
  • ArrayList feels superior to LinkedList for random access to GET and set because LinkedList moves the pointer.
  • For add and remove operations, LinedList has an advantage because ArrayList moves data.

Tell us the difference between Vector and ArrayList:

  • Vector’s methods are Synchronized and thread-safe, whereas ArrayList’s are not. Because synchronization of threads necessarily affects performance,ArrayList performs better than Vector.
  • When an element in a Vector or ArrayList exceeds its initial size,Vector doubles its capacity, whereas ArrayList increases its size by only 50%. ArrayList helps save memory.
  • We can also use the Collections. SynchronizedList to generate a List of thread safety

Talk about the difference between HashSet and TreeSet:

  • TreeSet is implemented by binary tree. Data in TreeSet is automatically sorted and null values are not allowed.
  • A HashSet is an implementation of a hash table. The data in a HashSet is unordered, and null can be placed in a HashSet, but only one NULL can be placed in a HashSet. The values in both cannot be repeated, just like a unique constraint in a database.
  • A HashSet requires that all objects put into it implement the HashCode() method. Objects put into it are identified by a HashCode, whereas String objects with the same content have the same HashCode, so the contents cannot be repeated. But objects of the same class can fit into different instances.

Talk about the difference between HashMap and HashTable:

  • HashMap is not thread-safe, whereas Hashtable is thread-safe, so Hashtable is a bit heavier because it uses the synchronized keyword to ensure thread-safe.
  • A HashMap allows both a key and a value to be null, whereas a Hashtable cannot be null.
  • A HashMap Iterator is a fail-fast Iterator, whereas a Hashtable enumerator is not a fail-fast Iterator. So when there are other threads to change the structure of a HashMap (add or remove elements), will throw ConcurrentModificationException, But the iterator itself the remove () method removes elements will not throw ConcurrentModificationException

The above are the basics of our collection, and here are some more advanced interview questions

Can you summarize the ArrayList in depth

  • The default array size of the no-argument construct is 10
  • An ArrayList iterates through a for loop faster than an iterator
  • The first step is to determine whether it needs to be expanded (that is, by calculating the current length of my array and the sum of the length I want to add to the array, minCapacity is compared with the current capacity. If necessary, the first expansion is carried out. The capacity of the first expansion is 1.5 times of the original capacity. If the minCapacity is still small, expand the capacity to minCapacity again. If the minCapacity is larger than the maximum capacity, expand the capacity to about 2.1 billion

Why is the elementData of an ArrayList decorated with transient

  • ArrayList implements the Serializable interface, which means that ArrayList can be serialized, and modifying elementData as transient means THAT I don’t want the elementData array to be serialized
  • When I serialize an ArrayList, the elementData in the ArrayList may not be full. Let’s say elementData is 10 in size, but I only use three of them. Is it necessary to serialize the entire elementData? This is obviously not necessary, so the writeObject method is overridden in ArrayList.

Have you overridden hashcode and equals? Why do you have to override hashcode to override equals?

  • If two objects are equal, the Hashcode must also be the same
  • If two objects are equal, calling equals on both objects returns true
  • Two objects have the same hashCode value, and they are not necessarily equal
  • Therefore, if equals is overridden, hashCode must be overridden as well
  • The default behavior of hashCode() is to generate unique values for objects on the heap. If hashCode() is not overridden, the two objects of the class will never be equal anyway (even if they point to the same data)

How does a HashSet check for duplicates

When you add an object to a HashSet, the HashSet evaluates the object’s Hashcode value to determine where it was added. It also compares the object’s Hashcode value to other added objects. If there is no matching Hashcode, the HashSet assumes that the object is not repeated. But if objects with the same Hashcode value are found, the equals() method is called to check whether objects with hashCode equality are really the same. If they are the same, the HashSet will not let the join succeed.

Talk about the underlying implementation of HashMap

JDK1.8 before

Before JDK1.8, the underlying HashMap was a combination of arrays and lists, known as list hashes. The HashMap uses the hash function of the key’s hashCode to get the hash value, and then uses (n-1) &hash to determine where the current element is stored (where n refers to the length of the array). If there is an element in the current position, Determine whether the hash value and key of the element are the same as those of the element to be saved. If they are, overwrite them directly. If they are not, solve the conflict by zipping.

The perturbation function refers to the hash method of the HashMap. The use of hash methods, known as perturbed functions, is intended to prevent some poorly implemented hashCode() methods, in other words, to reduce collisions.

After JDK1.8

Compared to the previous version, after JDK1.8 in solving the hash conflict with the larger changes, when the chain length of the table is greater than the threshold value (the default is 8) (convert list into red and black tree before judgment, if the current is less than 64 the length of the array, so choose to array capacity, rather than into a red and black tree), the list can be converted to a red-black tree, To reduce search time.

So can you talk about red black trees

First of all, we know that the red-black number is a binary search tree, which has the following characteristics

  • The value of all nodes in the left subtree is less than or equal to its root.
  • The value of all nodes in the right subtree is greater than or equal to its root.
  • The left and right subtrees are also binary sort trees respectively.

But the general binary tree in extreme cases, may become linear search, then lose its search property significance, while the red black tree is a self-balanced tree, it is most important to add the following three rules to ensure its self-balance

  • Each leaf node is a black empty node (NIL node).
  • Two children of each red node are black. (No two consecutive red nodes on all paths from each leaf to the root)
  • All paths from any node to each of its leaves contain the same number of black nodes.

Here small 66 said, red black tree is still very complicated, so generally not to ask, if the abnormal point, will also ask the process of self-balance, HERE I will not explain, we go to find. Its discoloration, its left rotation, right rotation, ha ha indeed hair loss.

Why is the length of a HashMap a power of 2

  • First, the odd rows will not work. When calculating the hash position in the array, the calculation method will be (n-1) &hash. Odd n-1 will be even, and the end of the even base 2 will be 0, and the end of the & operation will be 0, which will increase the hash conflict, and half of the space will have no data
  • Why can’t a power of two be a multiple of two, like 6,10?
    • The structure of a hashmap is an array, and the structure inside each array is node (linked list or red-black tree). Normally, if you want to put data in a different location, you will want to take the remainder of the data and place it in that location, using the hash % n formula. In computers, (n-1) &hash, when n to the 2nd power, satisfies a formula :(n-1) &hash = hash % n, which is more efficient.
    • Only numbers that are powers of two after n minus one, binary must be… A format such as 11111111, where the position (&) computed is entirely determined by the generated hash class, not by n-1(the binary length of the number of groups). You might be thinking, wouldn’t it be better to be affected, and then you calculate it again, and like a perturbation function, the hash collision is probably lower, and you have to take into account the expansion, 2 to the power of 2, and in binary like 4 and 8, which means 2 to the power of 2 and 3, Their binary structure is similar, for example, 4 and 8 00000100 0000 1000 only move the high hash forward one bit. In this way, when expanding capacity, you only need to judge the high hash and move it to the multiple of the previous position, without recalculating the position.

Why is HashMap’s expansion log 0.75

  • When the load factor is 1.0, it means that the expansion will not occur until all eight values of the array (represented in this diagram) are filled. This is a big problem because Hash conflicts are inevitable. When the load factor is 1.0, that means a lot of Hash collisions, and the underlying red-black tree becomes extremely complex. It is extremely detrimental to query efficiency. In this case, time is sacrificed to ensure space utilization.
  • When the load factor is 0.5, this means that when the array is half full, since there are fewer elements to fill, Hash collisions are reduced, and the length of the underlying list or the height of the red-black tree is reduced. Query efficiency will increase.
  • Basically the answer to why 0.75 comes out, it’s a tradeoff between time and space.

Conditions for HashMap treification

This small 66 said, if not read the source code, certainly not so deep impression

  • The first one must have been a hash collision
  • And lists that are larger than 8 will tree and smaller than 6 will degenerate
  • Another condition is that the entire HashMap has a capacity greater than 64

JDK1.7: Hashmap immutable loop

Under small also said roughly, it is 1.7 in the case of multi-threaded, expansion, assuming two threads at the same time expansion led to our list of references, each other to death cycle, which is what we call the list end plug, in fact this is not a bug, because official say the hashmap should not be used in a multithreaded environment, specific people to baidu

Talk about the PUT operation of a HashMap

  • The first step of course is to calculate the hash value of the key (processed (h = key.hashcode ()) ^ (h >>> 16)).
  • The second step is to use the putval method and determine if the container is empty. If so, expand the container.
  • The third step, the maximum capacity and hash value ampersand (I = (n-1) &hash), determine whether the array index has data, if not, put it in. Also check the key’s equals method to see if it needs to be overridden.
  • Step 4, if there is a collision, then continue traversing to determine whether the length of the list is greater than 8, if so, continue to change the current list into a red-black tree structure.
  • Step five, if it doesn’t go to 8, store the data directly at the end of the list
  • Step 6, finally add the container capacity +1.

Talk about the hashMap resize operation

  • If the capacity reaches the maximum, the current bucket is returned and no expansion operation is performed. Otherwise, the capacity is doubled and the expanded bucket is returned.
  • Modify the attribute values of other member variables based on the expanded bucket.
  • Create a new expanded bucket based on the new capacity and update the bucket references;
  • If there are elements in the original bucket, you need to transfer the elements;
  • Element collision and red-black tree conversion should be considered in element transfer.
  • During capacity expansion, the head nodes of the linked list are removed from the original bucket one by one, and all elements in the linked list are recalculated for hash allocation.
  • When a collision occurs, add the new element to the end;
  • Both low and high values need to be manipulated when elements are copied.

Compare ConcurrentHashMap 1.7 and 1.8

ConcurrentHashMap is a class in the ConcCurrent family. Because it supports concurrent operations efficiently and is widely used, the classical open source framework Spring uses ConcurrentHashMap to implement the underlying data structures. It’s already a step up from its thread-safe big brother, HashTable, and as a result its locks are more detailed than the synchronized locks that HashTable adds to almost every method, which can undoubtedly affect performance.

In 1.7 and 1.8, the idea of thread safety has been completely changed, in which the original Segment locking is abandoned, and CAS + synchronized is adopted to ensure concurrency security. It follows the philosophy of its contemporary version of HashMap, with the underlying “array” + linked list + red-black tree thinking.

  • Use node instead of segment to reduce lock granularity.
  • Designed the MOVED state while thread 2 is still putting data in the process of resize, thread 2 will help resize.
  • Instead of locking, three CAS operations are used to ensure atomicity of some node operations.
  • SizeCtl uses different values to represent different meanings and controls.

Talk about the sizeCtl of ConcurrentHashMap

  • A negative value indicates that initialization or capacity expansion is in progress
  • -1 indicates initialization
  • -n Indicates that N-1 threads are performing capacity expansion
  • A positive value or 0 indicates that the hash table has not been initialized. This value indicates the size of the initialization or next expansion, which is similar to the concept of expansion threshold. As you will see later, its value is always 0.75 times the capacity of the current ConcurrentHashMap, which corresponds to loadFactor.

Talk about the Put method of ConcurrentHashMap

  • The first step, as soon as you go in, is to make sure that the key value is null and if it is null throw an exception
  • In the second step, when adding a pair of key-value pairs, it first determines whether the array holding these key-value pairs is initialized, and if not, it initializes the array.
  • The third step is to compute the hash value to determine which position to place in the array. If this position is empty, add it (CAS lock). If it is not empty, fetch the node
  • Step 4, if the hash value of the fetched node is MOVED(-1), it means that the array is being expanded, copied to a new array, and the current thread will help with the replication
  • Step 5: If the node is not empty or expanded, use synchronized to lock and add the node
  • The sixth step, if it is a linked list, traverses the whole list until the keys of the extracted nodes are compared with the keys to be placed. If the keys are equal and the hash value of the keys is equal, it indicates that they are the same key and the value is overwritten; otherwise, it is added to the end of the linked list
  • Seventh, if it is a tree, call putTreeVal to add the element to the tree
  • Finally, after the addition is complete, it determines how many nodes there are at the node. If there are more than eight nodes, it calls the treeifyBin method to try to convert the list to a tree or expand the number

At the end

This is some basic interview questions, of course, there are many may not be so complete, but if you can answer these questions, in fact, the Java foundation is quite solid.

Daily for praise

Ok, everybody, that’s all for this article, you can see people here, they are real fans.

Creation is not easy, your support and recognition, is the biggest motivation for my creation, we will see in the next article

Wechat search “six pulse Excalibur program life” reply 888 I find a lot of information to you