3 W word long text, java basic interview questions! It's amazing!!!

Programmer 2021-04-08 11:26:55
word long text java basic


hey guys , It's also the interview season ,cxuan I'm going to write it again Java Relevant interview questions , Let's start with the basics , These interview questions belong to the basic series , Does not include multithreading related interview questions and JVM Relevant interview questions , Multithreading and JVM I put it in the back , I won't say much about it next , start doing sth. !

Java The basic chapter

Java What are the characteristics of

  • Concurrent : You can execute many statements in it , You don't have to do it all at once
  • Object oriented : Class based and object-oriented programming languages .
  • Independent : Support Write once , Run anywhere Independent programming language of , The compiled code can support Java On all platforms .

Java Characteristics of

Java The following are the features of

  • Simple ,Java It will make your work easier , Enables you to focus on the main business logic , You don't have to care about the pointer 、 Operator overloading 、 Memory recycling and other functions unrelated to the main business .
  • Portability ,Java It's platform independent , This means that any application written on one platform can be easily ported to another platform .
  • Security , After compiling, all the code will be converted to bytecode , Humans can't read . It makes development virus-free , Tamper free system / Applications become possible .
  • dynamic , It has the ability to adapt to changing environments , It can support dynamic memory allocation , This reduces memory waste , Improved application performance .
  • Distributed ,Java The functionality provided helps to create distributed applications . Use Remote method call (RMI), A program can call another program's method and get the output through the network . You can access files by calling methods from any computer on the Internet . It's a revolutionary feature , It's so important for today's Internet .
  • Robustness, ,Java It has powerful memory management function , Checking code at compile and run time , It helps to eliminate mistakes .
  • High performance ,Java The darkest technology is bytecode programming ,Java The bytecode that the code is compiled into can be easily converted to local machine code . adopt JIT Real time compiler to achieve high performance .
  • Explanatory ,Java Be compiled into bytecode , from Java Runtime environment interpretation .
  • Multithreading ,Java Support multiple execution threads ( Also known as lightweight processes ), Includes a set of synchronization primitives . This makes it easier to program with threads ,Java Thread safety is realized through the management model .

What are the characteristics of object-oriented

There are three main characteristics of object-oriented

  • encapsulation : Encapsulation is one of the characteristics of object-oriented , Is the main feature of object and class concepts . encapsulation , That is to encapsulate objective things into abstract classes , And classes can keep their data and methods to trusted classes or objects , Hiding information from untrusted sources .

  • Inherit : Inheritance refers to using all the functions of an existing class , And extend these functions without having to rewrite the original class .

  • polymorphic : Polymorphism is a technique that allows you to set a parent object equal to one or more of its children , After the assignment , The parent object can then behave differently depending on the properties of the child object currently assigned to it . To put it simply , In a word : Allows assigning a pointer of a subclass type to a pointer of a parent type .

JDK and JRE What's the difference?

  • JRE Its English name is Java Runtime Environment,Java Runtime environment . It mainly consists of two parts ,jvm Standard implementation and Java Some basic class libraries of . It is relative to the jvm Come on , What's more is part of Java Class library .
  • JDK Its English name is Java Development Kit,Java Development kit .jdk As a whole Java The core of development , It integrates jre And some handy gadgets . for example :javac.exe,java.exe,jar.exe etc. .

Here's another explanation JVM What is it?

  • JVM Its English name is Java Virtual Machine, Refers to Java virtual machine .Java Virtual machine is the core of cross platform implementation

For the most part ,JRE、JDK and JVM The relationship is as follows

Describe the difference between value passing and reference passing

If you want to really understand , You can refer to this article : https://www.zhihu.com/question/31203609

In a nutshell, it is

Value passed Copy a copy of the actual parameter to the function when it is called , In this case, if the function modifies the formal parameter passed by it , Will not affect the actual parameters

reference It refers to passing the address of the object directly to the function when calling the function , If you are modifying formal parameters , Will affect the value of the actual parameter .

== and equals What's the difference

== yes Java One of the operators in , It has two ways of comparison

  • about Basic data type Come on , == It's on both sides value Whether it is equal or not
public class DoubleCompareAndEquals {
Person person1 = new Person(24,"boy");
Person person2 = new Person(24,"girl");
int c = 10;
private void doubleCompare(){
int a = 10;
int b = 10;
System.out.println(a == b);
System.out.println(a == c);
System.out.println(person1.getId() == person2.getId());
}
}
  • about Reference type Come on , == It's on both sides quote Whether it is equal or not , That is to determine whether two objects point to the same memory area .
private void equals(){
System.out.println(person1.getName().equals(person2.getName()));
}

equals yes Java The parent class of all objects in , namely Object A method defined by a class . It can only compare objects , It indicates whether the values of both sides of the reference are equal . So remember , Is not to say that == The comparison is whether the references are equal ,equals The comparison is the value , This needs to be distinguished between the two .

equals As a comparison between objects, it has the following characteristics

  • reflexivity : For any non empty reference x Come on ,x.equals(x) Should return to true.
  • symmetry : For any non empty reference x and y Come on , if x.equals(y) by true, be y.equals(x) Also for the true.
  • Transitivity : For the value of any non null reference , There are three values ,x、y and z, If x.equals(y) return true,y.equals(z) return true, that x.equals(z) Should also return to true.
  • Uniformity : For any non empty reference x and y Come on , If x.equals(y) Equal words , Then they must always be equal .
  • Non emptiness : For the value of any non null reference x Come on ,x.equals(null) Must return false.

Java What are the basic data types in , How many bytes does each take up

stay Java in , The data type is only There are four categories and eight kinds

  • Integer type :byte、short、int、long

byte That's byte ,1 byte = 8 bits,byte The default value of is 0 ;

short Takes two bytes , That is to say 16 position ,1 short = 16 bits, Its default value is also 0 ;

int Take up four bytes , That is to say 32 position ,1 int = 32 bits, The default value is 0 ;

long Take up eight bytes , That is to say 64 position ,1 long = 64 bits, The default value is 0L;

So the byte size of integer type is long > int > short > byte

  • floating-point

Floating point has two data types :float and double

float It's a single precision floating point , Occupy 4 position ,1 float = 32 bits, The default value is 0.0f;

double It's a double precision floating point , Occupy 8 position ,1 double = 64 bits, The default value is 0.0d;

  • Character

The character type is char,char The type is a single 16 position Unicode character , The minimum is \u0000 ( That is to say 0 ), The maximum is \uffff ( That is to say 65535),char The data type can store any character , for example char a = 'A'.

  • Boolean type

Boolean means boolean,boolean There are only two values ,true Or is it false, It just means 1 position , The default value is false.

above x position They all refer to the occupation of memory .

String Medium equals How to rewrite

String It stands for Java Medium character string ,String Class is special , Its whole class is final Embellished , in other words ,String Cannot be inherited by any class , whatever modify String String method is to create a new string .

equals The method is Object Method of class definition ,Object Is the parent of all classes , And of course String,String Rewrote equals Method , Let's see how it was rewritten

  • First, we will judge the two strings to be compared, their quote Whether it is equal or not . If the references are equal , Go straight back to true , If not, continue with the following judgment
  • Then judge whether the object being compared is String Example , If not, go straight back false, If so , Compare the length of the two strings , If the length does not want to wait, then there is no need to compare ; If the length is the same , Will compare each of the strings character Whether it is equal or not , Once a character is not equal , It'll go straight back false.

Here's the flow chart

Here's another hint , You may be wondering when

if (this == anObject) {
return true;
}

How can this judgment statement return true? Because it's all strings , String comparison is not all heap space , Suddenly, I found that I would never leave , But you forget String.intern() Method , It represents concepts in different JDK There are different versions

stay JDK1.7 And subsequent calls intern The method is to determine whether there is a specified string in the runtime constant pool , If not , Just add the string to the constant pool , And returns the object in the constant pool .

The verification process is as follows

private void StringOverrideEquals(){
String s1 = "aaa";
String s2 = "aa" + new String("a");
String s3 = new String("aaa");
System.out.println(s1.intern().equals(s1));
System.out.println(s1.intern().equals(s2));
System.out.println(s3.intern().equals(s1));
}
  • First s1.intern.equals(s1) This will come back anyway true, because s1 When a string is created, it already exists in the constant pool .

  • Then the second statement returns false, because s1 Returns an object from a constant pool , and s2 The object returned is the object in the heap

  • The third sentence s3.intern.equals(s1), return true , because s3 Object although an object is created in the heap , however s3 Medium "aaa" Returns an object from a constant pool .

Why rewrite equals Method must override hashcode Method

equals Methods and hashCode All are Object The method defined in , They are often rewritten together .

equals Method is used to compare whether the object size is equal ,hashcode Method is used to judge each object hash A way to value . If only rewrite equals Method without overriding hashcode Method , It's likely to create two different objects , Their hashcode Also equal , Cause conflict . such as

String str1 = " conversation ";
String str2 = " important ";

Two of them hashcode equal , however equals It's not equal .

Let's take a look hashCode The official definition

In summary

  • If in Java Call the same object at run time hashCode After the method , No matter how many times you call , Should return the same hashCode, But in different Java In the program , perform hashCode Methods may return inconsistent values .
  • If I have two objects equals equal , that hashCode It has to be the same
  • If two objects equals It's not equal , that hashCode It could be the same , So we need to rewrite hashCode Method , Because you don't know hashCode The underlying structure of ( Anyway, I don't know , There is a big cow to teach ), So you need to rewrite hashCode Method , To generate different... For different objects hashCode value , This can improve the access speed of different objects .
  • hashCode This is usually achieved by converting the address to an integer .

two-object hashcode identical , that equals Whether it must be for true

This is not necessarily certain , Take a very simple example , You rewrote it hashcode Method , To calculate the remainder , So two objects hashcode It's likely to repeat , But there are two objects equals But not necessarily the same .

Even if you don't rewrite it hashcode Method , I'll give you a code example

String str1 = " conversation ";
String str2 = " important ";
System. out. println(String. format("str1:%d | str2:%d", str1. hashCode(),str2. hashCode()));
System. out. println(str1. equals(str2));

The output of the above two pieces of code is

str1:1179395 | str2:1179395
false

These two strings are equals Is not the same . in other words , Even if it is hashcode The same string ,equals It could be different .

String s1 = new String("abc") Several objects are created in memory

One or two ,String s1 It's a statement String Type of s1 Variable , It's not the object . Use new Keyword creates an object in the heap , Another object is abc , It creates... In the constant pool , So two objects are created ; If abc If it already exists in the constant pool , Then an object is created .

Please refer to another article of the author for details A different piece of String、StringBuffer、StringBuilder Detailed explanation

String Why is it immutable 、jdk In the source String How is it defined 、 Why is it designed this way? .

First of all, let's understand what is Immutable object , Immutable objects are created once , The internal state of its object cannot be modified , What do you mean ? In other words, immutable objects need to follow the following principles

  • The internal properties of immutable objects are final Of
  • The internal properties of immutable objects are private Of
  • Immutable objects cannot provide any way to modify the internal state 、setter No way
  • Immutable objects cannot be inherited and extended

Rather than ask String Why is it immutable , It's better to say how to put String Designed to be immutable .

String A class is an object , It is independent of Java Basic data types exist ,String You can think of it as a collection of strings ,String Is designed to final Of , Express String Once the object is created , Its value can no longer be modified , Any right String A method of creating a string value is to modify it .String After the object is created, it will exist in the runtime constant pool , The runtime constant pool is part of the method area ,JDK1.7 And moved it into the pile .

Immutable objects are not really immutable , Can pass Reflection To modify its internal properties and values , But generally we don't do this .

static What is the key word used for ? Talk about your understanding

static yes Java The most important keyword in ,static The concept of representation is Static , stay Java in ,static Mainly for

  • Modifying variables ,static The modified variable is called Static variables 、 Also known as Class variables , Class variables belong to class , For different classes ,static There's only one variable ,static The modified variable is in the method area ;static Modified variables can be passed directly through Class name . Variable name To visit , You don't have to instantiate classes to use again .
  • Modification methods ,static The method of modification is called Static methods , Static methods can go directly through Class name . Method name To use , Non static properties and methods cannot be used inside static methods
  • static Code blocks can be decorated , There are two main types , One is defined directly in a class , Use static{}, This is called Static code block , One is to define... In a class Static inner class , Use static class xxx To define .
  • static Can be used for static guided packets , By using import static xxx To achieve , This method is generally not recommended
  • static Can be used with singleton mode , The singleton pattern of thread safety is realized by double checking lock .

Please refer to this article for further understanding A little static It's hard to live in me ?

final What is the key word used for ? Talk about your understanding

final yes Java Keywords in , It means Immutable , stay Java in ,final Mainly for

  • decorator ,final Modified classes cannot be inherited , Not to be inherited means not to be used extends To inherit final Modified class .
  • Modifying variables ,final Modified variables cannot be rewritten , There are two meanings of not being rewritten , For basic data types ,final Decorated variable , Its value cannot be changed ,final Decorated object , Object references cannot be changed , But the properties inside the object can be modified .final The modified variable plays a role in a way immutable The effect of , therefore , Can be used to protect read-only data , Especially in concurrent programming , Because it's clear that we can't do it again final Variable assignment , It helps to reduce the extra synchronization overhead .
  • Modification methods ,final Methods that modify cannot be overridden .
  • final The modifier and Java Program performance optimization is not necessarily related to

What's the difference between an abstract class and an interface

Abstract classes and interfaces are Java Keywords in , Methods are allowed to be defined in both abstract classes and interfaces , It doesn't have to be implemented in a specific way . Both abstract classes and interfaces are allowed to be inherited , They are widely used in JDK And the source code of the framework , To implement polymorphism and different design patterns .

The difference is

  • Different levels of abstraction : class 、 abstract class 、 Interfaces are actually three different levels of abstraction , The order of abstraction is Interface > abstract class > class . In the interface , Only method definitions are allowed , No implementation of methods is allowed , Methods can be defined and implemented in abstract classes ; Only methods are allowed to be implemented in a class , The definition of a method is that it is not allowed to appear after a method {}
  • The keywords used are different : Class uses class To express ; Abstract class use abstract class To express ; Interface to use interface To express
  • Variable : Variables defined in an interface can only be public static constants , Variables in an abstract class are ordinary variables .

The difference between rewriting and overloading

stay Java in , Rewriting and overloading are different representations of the same method , Let's make a simple distinction between rewriting and overloading

  • The relationship between children and parents is different , Rewriting is different representations of children and parents , Overloading is a different representation in the same class ;
  • Different concepts , The method of subclass overriding parent class usually uses @override To express ; The method declaration and parameter type of the overridden method 、 The order must be exactly the same as the parent class ; Overloading is for concepts in the same class , It requires that the overloaded method must satisfy any of the following requirements : The order of method parameters , Number of parameters , The type of any parameter remains different .

Can constructors be overloaded , Can it be rewritten ?

This question tests your understanding of constructors .

We Java To create an object in is to call the construction method of the object , For example, the following code

InstanceObject IO = new InstanceObject() ; // A parameterless constructor was called
InstanceObject IO = new InstanceObject(xxx) ; // Called a construction method with parameters

And what is the concept of overloading ?

It means that we can define some methods with the same name , These methods are distinguished by defining different input parameters , And then when I call ,JVM It will be based on different parameter styles , To choose the right way to execute .

in other words , The concept of overloading is more about identical Different descriptions of naming methods . So the above code is obviously overloaded , Because the name is the same , I can judge whether there are parameters to call different construction methods for initialization .

So can constructors be rewritten ? Let's look at rewriting first

Rewriting is a subclass's rewriting of the implementation process of the parent's accessible methods , Neither the return value nor the parameter can be changed . From the conceptual definition of rewriting, we know that constructors cannot be rewritten .

First , Constructor has no return value , Second point , The name of the constructor must match the name of the class .

You can't be in class A Written in public A(); In the class B It's also written in Chinese public A() Well , This obviously can't be compiled .

byte What is the range of phi , How to work it out

byte The range of phi is zero -128 -> 127 Between , Is the total 256 individual . One byte Type occupies a byte in the computer , So that is 8 bit, So the biggest thing is 2^7 = 1111 1111.

Java of use Complement code To represent binary numbers , The highest bit of the complement is the sign bit , For the highest position 0 It means a positive number , highest 1 A negative number , The complement of a positive number is its In itself , Because the highest bit is the sign bit , So a positive number means 0111 1111 , That is to say 127. The biggest negative number is 1111 1111, There are two things involved 0 , One +0 , One -0 ,+0 Return to a positive number , That is to say 0 ,-0 Categorize as negative , That is to say -128, therefore byte The range of -128 - 127.

HashMap and HashTable The difference between

The same thing

HashMap and HashTable It's all based on hash table , Every element inside is key-value Key value pair ,HashMap and HashTable It's all done Map、Cloneable、Serializable Interface .

Difference

  • The father is different :HashMap Inherited AbstractMap class , and HashTable Inherited Dictionary class

  • Different null values :HashMap Allow empty key and value value ,HashTable Empty is not allowed key and value value .HashMap Will be able to Null key As ordinary key treat . Don't allow null key repeat .

  • Thread safety :HashMap Not thread safe , If multiple external operations are modified at the same time HashMap For example add Or is it delete, You have to synchronize , Just right key perhaps value Is not an operation to change the data structure . You can choose to construct thread safe Map such as Collections.synchronizedMap Or is it ConcurrentHashMap. and HashTable Is itself a thread safe container .
  • Performance aspect : although HashMap and HashTable It's all based on Single chain list Of , however HashMap Conduct put perhaps get􏱤 operation , Can achieve constant time performance ; and HashTable Of put and get All operations are added synchronized The lock , So it's inefficient .

  • The initial capacity is different :HashTable The initial length of is 11, After each expansion, the capacity becomes the same as before 2n+1(n For the length of the last time ) and HashMap The initial length of is 16, After that, each expansion was doubled . Creation time , If the initial value of capacity is given , that HashTable Will directly use the size you give , and HashMap It will be expanded to 2 Power of .

HashMap and HashSet The difference between

HashSet Inherited from AbstractSet Interface , Realized Set、Cloneable,、java.io.Serializable Interface .HashSet Duplicate values in the collection are not allowed .HashSet The bottom is actually HashMap, All right HashSet In fact, the operation of is to HashMap The operation of . therefore HashSet It doesn't guarantee the order of the sets , It's not a thread safe container either .

HashMap Bottom structure of

JDK1.7 in ,HashMap use Position bucket + Linked list The implementation of the , That is to use Linked list To deal with conflict , same hash The linked list of values is stored in an array . But when there are more elements in a bucket , namely hash When there are many elements with equal values , adopt key The efficiency of finding values in turn is low .

therefore , And JDK 1.7 comparison ,JDK 1.8 Some changes have been made in the underlying structure , When the element in each bucket is greater than 8 When , It will turn into a red black tree , The goal is to optimize query efficiency .

HashMap Why is the length of 2 Power square

I've been thinking about this for a few days , When I was discussing the daily question with my friends in the group , Ask them why length%hash == (n - 1) & hash, They say that the premise of equality is length The length of 2 Power square , And then I came back with a question, is it length Can it be 2 To the power of ? Actually, I don't understand causality , because HashMap Is the length of the 2 Power square , So we use the remainder to determine the subscript in the bucket . If length The length of is not 2 Power square , Let's give you an example

For example, the length is 9 When ,3 & (9-1) = 0,2 & (9-1) = 0 , All in 0 On , The collision ;

This will increase HashMap The probability of collision .

HashMap Multithreading causes a dead loop problem

HashMap Not a thread safe container , In high concurrency scenarios , You should use ConcurrentHashMap, Use in multithreading scenarios HashMap It's going to cause a loop problem ( be based on JDK1.7), The problem lies in rehash It's about , That is to say

do {
Entry<K,V> next = e.next; // <-- Suppose that the thread is scheduled to suspend as soon as it gets there
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
} while (e != null);

This is a JDK1.7 Of rehash code snippet , In a concurrent scenario, a loop is formed .

JDK1.8 It can also cause a dead circle problem .

HashMap What are the implementations of thread safety

because HashMap Not a thread safe container , Therefore, it is recommended to use ConcurrentHashMap , Or thread safety HashMap, Use Collections Thread safe container under package , for instance

Collections.synchronizedMap(new HashMap());

You can also use HashTable , It's also a thread safe container , be based on key-value Storage , Frequently used HashMap and HashTable It's because HashTable Data structure and HashMap identical .

The most efficient one is ConcurrentHashMap.

Let's talk about HashMap put The process of

First of all, I will use hash Function to calculate key, Then the actual insertion method is executed

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// If table by null Or not for table Allocate memory , Just resize once
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// Appoint hash If the value node is empty, insert it directly , This (n - 1) & hash It's the real hash in the table
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
// If it's not empty
else {
Node<K,V> e; K k;
// Calculate the actual hash value in the table with the... To be inserted key.hash comparison
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// If it's different , And the current node is already in TreeNode Yes
else if (p instanceof TreeNode)
// Using red and black tree storage
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// key.hash Different and no longer TreeNode On , Find it on the linked list p.next==null
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
// Insert... At the end of the watch
p.next = newNode(hash, key, value, null);
// After adding new nodes, if the number of nodes reaches the threshold , entering treeifyBin() Make a second judgment
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// If you find the same hash、key The node of , So just exit the loop
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
// to update p Point to next node
p = e;
}
}
// map Contains old values in , Return old value
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
// map Adjustment times + 1
++modCount;
// The number of key value pairs reaches the threshold , Need to expand
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}

HashMap put The core of the method is in putval Method , The insertion process is as follows

  • First of all, I will judge HashMap Is it a new build , If so, it will be done first resize
  • Then determine the element to be inserted in HashMap Is there already ( The collision shows that ), If it doesn't exist , Generate new k-v Node storage , Then judge whether it needs to be expanded .
  • If the element to be inserted already exists , It means there's a conflict , This will be converted into a linked list or a red black tree to resolve the conflict , First of all, judge the... In the linked list hash,key Whether it is equal or not , If it's equal , Replace the old value with the new value , If the node belongs to TreeNode type , It will be processed directly in the red and black trees , If hash ,key Neither equal nor belong to TreeNode type , Will be directly converted to linked list processing , Traverse the linked list , If the linked list next Node is null, Determine whether to convert to a red black tree , If you don't convert , Find... In the traversal process key Exactly equal nodes , Replace the old node with a new node

About HashMap Please refer to this article for further understanding After reading this HashMap , It's OK to argue with the interviewer

ConcurrentHashMap Underlying implementation

ConcurrentHashMap It's thread safe Map, It is also the preferred data structure in high concurrency scenarios ,ConcurrentHashMap The bottom layer is to use Section lock To achieve .

Integer Buffer pool

Integer The cache pool is IntegerCache , It is Integer The static inner class of .

Its default value is used for caching -128 - 127 Number between , If there is -128 - 127 Between the numbers , Use new Integer You don't have to create objects , It is retrieved directly from the cache pool , This reduces the allocation of objects in the heap , To improve the efficiency of the program .

For example, create a Integer a = 24, It's actually called Integer Of valueOf , You can get this conclusion by decompiling

Then let's take a look at valueOf Method

If it is within the scope of the specified cache pool , It will return the cached value directly without creating a new one Integer object .

The size of the cache can be used XX:AutoBoxCacheMax To specify the , stay VM On initialization ,java.lang.Integer.IntegerCache.high Properties are set and saved in sun.misc.VM In the private system properties of .

UTF-8 and Unicode The relationship between

Because each country has its own unique character code , therefore Unicode The aim of this development is to create a new standard , Used to map characters in most languages in use today , Some of these characters are not necessary , But it's essential for creating text .Unicode Unified encoding of all characters , It's a Character Set, Character set , Character set just gives all characters a unique number , But there's no rule on how to store it , Different characters have different storage space , Some need a byte to store , Some need it 2、3、4 Bytes .

UTF-8 It's just that a lot of text characters can be decode One way , It's a way of getting longer .UTF-8 representative 8 Bit group representation Unicode Format of characters , Use 1 - 4 Bytes to represent characters .

U+ 0000 ~ U+ 007F: 0XXXXXXX
U+ 0080 ~ U+ 07FF: 110XXXXX 10XXXXXX
U+ 0800 ~ U+ FFFF: 1110XXXX 10XXXXXX 10XXXXXX
U+10000 ~ U+1FFFF: 11110XXX 10XXXXXX 10XXXXXX 10XXXXXX

You can see ,UTF-8 The variable length is realized by the number of flag bits at the beginning . For single byte characters , One byte only , Achieve downward compatibility ASCII, And can be with UTF-32 equally , contain Unicode All characters in , It can also effectively reduce the space occupied in the process of storage and transmission .

Sure , because Unicode Coding adopted 2 Byte code ,UTF-8 yes Unicode An implementation of , It uses a variable length character set for encoding ,char c = ' in ' It's two bytes , So it can be stored . legal .

Arrays.asList yes Array One of the static methods in , It can convert arrays into List Sequence , We need to pay attention to the following points

  • Arrays.asList After conversion List No more structural changes can be made , What is structured modification ? Just can't do anything more List The operation of adding or decreasing elements .
public static void main(String[] args) {
Integer[] integer = new Integer[] { 1, 2, 3, 4 };
List integetList = Arrays.asList(integer);
integetList.add(5);
}

The result will be thrown out directly

Exception in thread "main" java.lang.UnsupportedOperationException

We can find the problem by looking at the source code

// This is a java.util.Arrays The inner class of , instead of java.util.ArrayList
private static class ArrayList<E> extends AbstractList<E>
implements RandomAccess, java.io.Serializable

Inherit AbstractList Chinese vs add、remove、set The method is to throw the exception directly , In other words, if the inherited subclass does not override these methods , Then the instance of subclass will throw exception directly when calling these methods .

Here is AbstractList Definition of method in , We can see the specific exception thrown :

public void add(int index, E element) {
throw new UnsupportedOperationException();
}
public E remove(int index) {
throw new UnsupportedOperationException();
}
public E set(int index, E element) {
throw new UnsupportedOperationException();
}

although set The method also throws a field , But because of Inner class ArrayList Rewrote set Method , So it can modify the elements .

  • Arrays.asList Conversion of underlying types is not supported

Java Basic data types in (byte,short,int,long,float,double,boolean) Does not support the use of Arrays.asList Method to convert

Collection and Collections The difference between

Collection and Collections It's all in java.util Class under package

Collection Is the parent of a collection class , It's a top-level interface , Most abstract classes, such as AbstractListAbstractSet All inherited Collection class ,Collection Class defines only one section of standard methods, such as add、remove、set、equals etc. , Concrete methods are implemented by abstract classes or implementation classes .

Collections It is a tool class of collection class ,Collections Provides some basic use of tool classes

  • sort Method , Sort the current set , Realization Comparable The class of the interface , Only one sort scheme can be used , This is called natural comparison
  • For example, a container that implements thread safety Collections.synchronizedListCollections.synchronizedMap etc.
  • reverse reverse , Use reverse Methods can be based on the natural order of the elements Sort the specified list in descending order .
  • fill, Replace all elements in the specified list with the specified elements .

There are many uses , Readers can read it Collections Check the source code of ,Collections Cannot instantiate , therefore Collections The methods in are all made by Collections. Method Call directly .

You know, fail-fast and fail-safe Do you

fail-fast yes Java One of the Fast failure Mechanism ,java.util All the collections under the package fail quickly , A quick failure throws ConcurrentModificationException abnormal ,fail-fast You can think of it as a quick detection mechanism , It can only be used to detect errors , Will not recover from errors ,fail-fast Not necessarily only in Multithreading It exists in the environment ,ArrayList This exception will also be thrown , The main reason is that modCount It's not equal to expectedModCount.

fail-safe yes Java One of the Security failure Mechanism , It means that when traversing, it does not directly access the original collection , Instead, copy the contents of the original collection first , Traversing over the set of copies . Because the iteration is to traverse the copy of the original set , Therefore, changes made to the original set during traversal cannot be detected by the iterator , So it doesn't trigger ConcurrentModificationException.java.util.concurrent The containers under the package are all security failed , It can be used in multi-threaded condition , Concurrent modification .

ArrayList、LinkedList and Vector The difference between

It's a cliche too

ArrayList、LinkedList、Vector It's all in java.util The tool class under the package , They're all implemented List Interface .

  • ArrayList At the bottom of is a dynamic array , It is based on the characteristics of arrays , therefore ArrayList Traversal access is very fast , But the additions and deletions are slow , Because it involves copying arrays .ArrayList Is a non thread safe container , In concurrent scenarios, it can cause problems , If you want to use thread safe containers , Recommended Collections.synchronizedList;ArrayList When expanding, it will increase 50% The capacity of .
  • LinkedList At the bottom of the list is a double linked list , therefore LinkedList The addition and deletion of are very fast , Just delete the element , Point the respective pointer to the new element . however LinkedList Traversal is slow , Because only when you visit one element at a time can you know the value of the next element .LinkedList It's also a non thread safe container , Recommended Collections.synchronizedList
  • Vector Vector is the first set container to appear ,Vector Is a thread safe container , Every method of it is roughly added with synchronized lock , So its addition and deletion 、 Traversal efficiency is very low .Vector During the expansion , Its capacity will double .

Exception and Error What's the difference?

Exception It refers to abnormal ,Exception There are two kinds of anomalies , One is an exception during compilation , be called checkedException , One is an exception that occurs during program running , be called uncheckedException, common checkedException Yes IOException,uncheckedException Collectively referred to as RuntimeException, common RuntimeException There are mainly NullPointerExceptionIllegalArgumentExceptionArrayIndexOutofBoundException etc. ,Exception Can be captured .

Error It refers to an error in the running process of a program , Usually it will cause the program to crash ,Error It's usually irreversible ,Error Can't be captured .

Please refer to this article for details After reading this Exception and Error , It's OK to argue with the interviewer

String、StringBuilder and StringBuffer What's the difference?

String In particular, it means Java String in ,String Class is located java.lang It's a bag ,String Class is created by final Embellished ,String Once created, a string cannot be modified , Any right String The modification operation is equivalent to re creating a string .String The underlying use of strings StringBuilder To achieve

StringBuilder be located java.util It's a bag ,StringBuilder It's a non thread safe container ,StringBuilder Of append Methods are often used for string concatenation , It's more efficient than String in + The stitching efficiency of No .StringBuilder It is not generally used in concurrent environments

StringBuffer be located java.util It's a bag ,StringBuffer Is a thread safe container , In multithreading scenario, we usually use StringBuffer Used as a concatenation of strings

StringBuilder and StringBuffer All inherited from AbstractStringBuilder class ,AbstractStringBuilder Class implements the StringBuffer and StringBuilder General operation of .

For further understanding, please refer to this article In depth understanding of String、StringBuilder and StringBuffer

What is the principle of dynamic agent

Agents are generally divided into Static proxy and A dynamic proxy , They are all applications of the proxy pattern , Static proxy means that the program has been compiled before it runs , The program knows who will execute the proxy method .

The dynamic proxy can only be determined during the running of the program , Compared to static agents , The advantage of dynamic agent is that it is very convenient to handle the functions of agent class uniformly , Instead of modifying the methods in each proxy class . It can be said that dynamic proxy is based on Reflection Realized . By reflection we can directly manipulate classes or objects , For example, get the definition of a class , Get declared properties and methods , Calling method , The definition of a class can be modified at run time .

A dynamic proxy is a way to build an agent at run time 、 The mechanism for dynamically handling method calls . There are many ways to implement dynamic proxy ,Java The agent provided is called JDK A dynamic proxy ,JDK Dynamic proxies are class based inheritance .

You can refer to this article to understand dynamic agents Deep understanding of dynamic agent

Several ways to realize dynamic proxy

I'll give you four ways to implement dynamic proxy , Namely

  • JDK A dynamic proxy :JDK So is dynamic agent Java A dynamic proxy , It's an interface based dynamic proxy , It usually proxy all classes under the interface .
  • CGLIB A dynamic proxy :CGLIB A dynamic proxy It's about implementing proxies for classes , It is mainly to generate a subclass for the specified class , The way to cover it , in other words CGLIB Dynamic proxies use class inheritance -> Method rewriting .
  • Javassist agent :Javassist Is in Java Class library for editing bytecode in ; It makes Java A program can define a new class at run time , And in JVM Load the class file when you modify it .
  • ASM agent :ASM It's a set Java Bytecode generation architecture , It can dynamically generate subclasses or other proxy classes in binary format , Or in the class is Java Before the virtual machine is loaded into memory , Dynamically modify classes .

The implementation of these four bytecodes can be referred to Dynamic proxy is so simple !

Explain Serialization and Deserialization

Serialization Represents serialization , Objects that implement serialization and deserialization must implement serializable Interface , Serialization is to turn an object into a byte stream , Storage to disk or network . Deserialization is the process of deserializing .

I often have a question when I learn serialization , Why objects need to be serialized ?

For the purpose of data transmission , Because this object is in object format in your code , But it's not an object format in the process of transmission , therefore , When other processes or machines want to communicate with you , Both of you will send all kinds of data , It's also possible to send this object , So this object is bound to be converted to a format that can be recognized in the network or disk , Binary .

That means , The sender needs to send this Java Object to byte sequence , To transmit... Over the network ; The receiver needs to restore the byte sequence to Java object , This is also Deserialization Interface .

int and Integer The difference between

int and Integer There are too many differences

  • int yes Java Basic data types in ,int It stands for integer , One int Occupy 4 byte , That is to say 32 position ,int The initial value of is the default value of 0 ,int stay Java The memory model is allocated in the stack ,int There is no way .
  • Integer yes Java The wrapper class of the basic data type in ,Integer It's an object ,Integer You can make method calls ,Integer The default value of is null,Integer stay Java The memory model is allocated in the heap .int and Integer It can be converted to each other in calculation ,int -> Integer The process is called Packing ,Integer -> int The process is called Unpacking ,Integer also IntegerCache , Will be automatically cached -128 - 127 The value in

For an in-depth understanding of unpacking and packing, please refer to this article Detailed explanation Java Automatic packing and unpacking in

Java What are provided I/O The way

Java I/O There are many ways , Conventional I/O Also known as BIO, The main streams are as follows .

Java I/O The implementation of the package is relatively simple , But it's prone to performance bottlenecks , Conventional I/O It's based on synchronous blocking .

JDK 1.4 And then there's NIO, Which is located in java.nio It's a bag , Provides the basis for channel、Selector、Buffer The abstraction of , Multiplexing can be built 、 Synchronous nonblocking I/O Program .

JDK 1.7 And then to NIO Further improvements were made , Introduced Asynchronous non-blocking The way , Also known as AIO(Asynchronous IO). It can be illustrated by living examples : The project manager gave his staff to change one bug, Then the project manager will not wait for the staff to solve it all the time bug, He must be working with the staff bug To assign to other subordinates bug Or do something else , Staff finished bug Then tell the project manager bug The solution is over. .

In depth understanding of IO You can refer to this article In depth understanding of IO .

Talk about the design patterns you know

A mind map to control the market

For example, global uniqueness can be used The singleton pattern .

have access to The strategy pattern Optimize too much if...else...

For standard setting Template Pattern

Take over someone else's pot , But I don't want to change the original class Adapter pattern

Use Combine Not inheritance

Use Decorator It can be made with sugar 、 Coffee with cheese

agent Can be used for any middleman ......

Write a few singleton mode implementation

This is also a common interview question , I don't usually let you write in singleton mode . Even if it's handwritten , Just write the key code . In fact, what this question wants to ask is how to realize the singleton pattern , And there's nothing wrong with each implementation .

Generally, you can answer like this

  • Hungry Chinese style : Thread safety , High call efficiency , But it can't delay loading
  • Slacker type : Thread safety , The call efficiency is not high , But it can delay loading
  • Double CheckLock Single case implementation :DCL That is, double lock judgment mechanism ( because JVM Underlying model reasons , Sometimes something goes wrong , Not recommended
  • Static inner class implementation pattern : Thread safety , High call efficiency , Can delay loading
  • Enumeration class : Thread safety , High call efficiency , No delay loading , It can naturally prevent reflection and deserialization calls

If you want to know more about this interview question , You can refer to I explained the singleton model to the interviewer , He gave me a thumbs up

Comparator and Comparable What's the difference

  • Comparable It's more like a natural sequence

  • Comparator It's more like a custom sort

At the same time, use Comparator( Custom sort ) Compare the rules of .

For some common data types ( such as String, Integer, Double…), They default to Comparable Interface , Realized compareTo Method , We can use it directly .

And for some custom classes , They may need to implement different comparison strategies in different situations , We can create a new Comparator Interface , Then use specific Comparator Implementation for comparison .

About Comparator and Comparable In depth understanding of , You can refer to this article Comparable and Comparator The understanding of the .

Object What methods do you usually have in a class

Object Class is the parent of all objects , It contains methods that all objects can use

  • hashCode(): Hash code used to compute objects
  • equals(): Used to compare whether the values between objects are equal
  • toString(): Used to convert an object into a string
  • clone(): For copying between objects
  • wait(): Used to implement waiting between objects
  • notify(): Used to notify objects to release resources
  • notifyAll(): Used to notify all objects to release resources
  • finalize(): Used to tell the garbage collector to recycle
  • getClass(): Used to get object classes

Java Generics and type erasures

About Java Generics and erasure is enough for one article .

The basic principle of reflection , What are the three ways reflection creates class instances

The reflex mechanism is to make Java The program runs with introspection (introspect) The ability of , Through reflection, we can directly manipulate classes and objects , For example, get the definition of a class , Get the properties and methods of the class , Construction method, etc .

The three ways to create class instances are

  • Object instances .getClass();
  • adopt Class.forName() establish
  • Object instances .newInstance() Method creation

An in-depth understanding of reflection , Please refer to After learning to reflect , I was admitted to !( dried food )

Strong citation 、 If quoted 、 The difference between virtual reference and phantom reference

The different types of references we're talking about are actually logical , For virtual machines , It mainly reflects the different objects Accessibility (reachable) Status and right garbage collection (garbage collector) Influence .

The following process can be used to summarize the life cycle of an object

Object is created and initialized , Object is used at run time , Then leave the scope of the object , Objects become unreachable and are recycled by the garbage collector . The area marked in red indicates that the object is in the strong reachable stage .

JDK1.2 It introduces java.lang.ref package , There are four stages in the life cycle of an object :􏲧 Strong reachability 􏰛(Strongly Reachable􏰜) Soft reachable (Soft Reachable􏰜) Weakly reachable (Weak Reachable􏰜) Phantom reach (Phantom Reachable􏰜).

If only objects eligible for garbage collection are discussed , So there are only three : Soft reachable 、 Weak reachability and phantom reachability .

  • Soft reachable : Soft reach is 􏱬 We can only use soft references 􏳂 Status to access , Soft reachable objects are defined by SoftReference Referenced object , And there are no strongly referenced objects . Soft references are used to describe some Useful but not necessary The object of . The garbage collector will keep soft reference objects for as long as possible , But it's going to happen OutOfMemoryError Before , Reclaim soft referenced objects . If soft referenced objects are recycled , If the memory is not enough , It will be thrown directly OutOfMemoryError.

  • Weakly reachable : Weakly reachable objects are WeakReference Referenced object . The garbage collector can collect weakly referenced objects at any time , Objects that do not attempt to retain soft references .

  • Phantom reach : Visional reach is achieved by PhantomReference Referenced object , Illusory reach is not strong 、 soft 、 Weak reference for Association , And it's been finalize After that , Only when the phantom reference points to this object .

besides , There are also two reachability judgment conditions of strong reachability and non reachability

  • Strong reachability : An object has just been created 、 initialization 、 All objects in use are in a strong reachable state
  • Unreachable (unreachable): Being in an unreachable object means that the object can be cleared .

Here is a transition diagram of different reachability States

Judge accessibility conditions , It's also JVM Part of the considerations that the garbage collector decides how to handle objects .

All object reachability references are java.lang.ref.Reference Subclasses of , It has a get() Method , Return reference object . If the reference object has been cleared by a program or garbage collector , This method returns null . in other words , Except for phantom references , Both soft reference and weak reference can get objects . And these objects can be artificial save , Become strong reference , For example, put this Key assigned to object , Just re associate with any object in the reference chain .

Deep understanding of citation issues , Take a look at this article Deep understanding of various citation issues .

final、finally and finalize() The difference between

It can be said that there is no connection between the three , We talked about ,final It can be used to modify a class 、 Variables and methods , You can refer to the above final The interview question .

finally It's a keyword , It is often associated with try Use blocks together , For exception handling . Use try...finally Code block type of ,finally Part of the code must be executed , So we are often in finally Method is used to close the resource .

JDK1.7 in , Recommended try-with-resources Closing resources gracefully , It directly uses try(){} Close the resource , You don't have to write finally Keyword. .

finalize yes Object One of the methods in the object , Recycling methods for objects , This method is generally not recommended ,finalize It's associated with garbage collection , stay Java 9 in , take finalize Mark for deprecated, If there is no special reason , Don't achieve finalize Method , Don't count on him to recycle .

In depth understanding of final、finally and finalize , Take a look at this one After reading this final、finally and finalize It's OK to argue with the interviewer .

What are the classifications of inner classes , Explain separately

stay Java in , You can put the definition of one class inside the definition of another class , This is it. Inner class . The inner class itself is an attribute of the class , Consistent with other attribute definitions .

There are four kinds of internal classes

  • Member inner class
  • Local inner classes
  • Anonymous inner class
  • Static inner class

Static inner class It is a static class defined inside a class , Static inner class can access all static variables of outer class , Non static variables of external classes are not accessible ;

Member inner class It is defined within a class , Non static class at member location , It's a member inner class . Member inner class can access all variables and methods of outer class , Including static and non static , Private and public .

The inner class defined in the method , Namely Local inner classes . The local class defined in the instance method can access all variables and methods of the external class , Local classes defined in static methods can only access static variables and methods of external classes .

Anonymous inner class It's an inner class without a name , Except for no name , Anonymous inner classes have the following features :

  • Anonymous inner class must inherit an abstract class or implement an interface
  • Anonymous inner classes cannot define any static members and static methods .
  • When the parameter of the method needs to be used by anonymous inner class , Must be declared as final.
  • Anonymous inner classes cannot be abstract , It must implement all the abstract methods of the inherited class or implemented interface .

Name a few common exceptions

  • NullPointerException: Null pointer exception
  • NoSuchMethodException: Method not found
  • IllegalArgumentException: Illegal parameter exception
  • IndexOutOfBoundException: Array subscript out of bounds exception
  • IOException: Because the file was not found 、 Not open or I/O The operation cannot be performed and causes an exception
  • ClassNotFoundException : Could not find the exception thrown by the file
  • NumberFormatException: Character UTF Code data format error causes exception ;
  • InterruptedException: Exception thrown by thread interrupt

The difference between static binding and dynamic binding

One Java The program has to be written 、 compile 、 Run three steps , Writing code is not within the scope of our discussion , So our focus will naturally be on compile and function These two stages , Because the compilation and run-time process is quite cumbersome , The following is my understanding :

Java Program from the creation of source files to the operation of the program to go through two major steps :

1、 Compile time is the process by which the compiler compiles the source file into bytecode

2、 Bytecode files are Java Virtual machine interpretation execution

binding

Binding is the process of calling a method and connecting it with the class calling the method, which is called binding .

There are two main types of binding :

Static binding and Dynamic binding

Other names for binding

Static binding == Pre binding == Compile time binding

Dynamic binding == Late binding == Runtime binding

For the convenience of distinguishing : The following is called static binding and dynamic binding

Static binding

Before the program runs , That's the compilation period JVM You can determine who called the method , This mechanism is called static binding

Identify the three keywords of static binding and their understanding

If a method consists of private、static、final Modified by any keyword , So this method is pre bound

The constructor is also pre binding

private:private Keyword means private , If you are private Decorated methods cannot be called by other classes other than this class , This is the unique method of this class , So it's up to the compiler to identify which class the method belongs to

public class Person {
private String talk;
private String canTalk(){
return talk;
}
}
class Animal{
public static void main(String[] args) {
Person p = new Person();
// private The method of modification is Person Class specific , therefore Animal Class not accessible ( Animals can't talk )
// p.canTalk();
}
}

final:final Methods that modify cannot be overridden , But it can be called by subclasses , If you declare a method as final Can effectively turn off dynamic binding

public class Fruit {
private String fruitName;
final String eatingFruit(String name){
System.out.println("eating " + name);
return fruitName;
}
}
class Apple extends Fruit{
// Can not rewrite final Method ,eatingFruit Method only belongs to Fruit class ,Apple Class cannot call
// String eatingFruit(String name){
// super.eatingFruit(name);
// }
String eatingApple(String name){
return super.eatingFruit(name);
}
}

static: static The modification method is special , No need to pass new Call a class , from Class name . Variable name Call this method directly , This is the key ,new Is the key , It can also be thought of as a trigger for polymorphisms , By the class name . If the variable name is called directly , In this case, the class name is determined , It doesn't produce polymorphism , The following code :

public class SuperClass {
public static void sayHello(){
System.out.println(" from superClass Say hello ");
}
}
public class SubClass extends SuperClass{
public static void sayHello(){
System.out.println(" from SubClass Say hello ");
}
public static void main(String[] args) {
SuperClass.sayHello();
SubClass.sayHello();
}
}

SubClass Inherit SuperClass after , stay

Yes, it can't be rewritten sayHello Methodical , in other words sayHello() Methods are hidden from subclasses , But you can write your own sayHello() Method , That is, subclasses SubClass Of sayHello() Method , thus it can be seen , Method by static The key words modify , It's also compile time binding

Dynamic binding

Binding at runtime depends on the type of specific object

Except by private、final、static Besides the modified method and construction method ,JVM The process of determining which object a method is called at run time is called dynamic binding

If you compile 、 Run as a timeline , Before running, the program must be compiled , Then the binding at compile time is a pre binding , When the program is running , The binding that happens is late binding .

public class Father {
void drinkMilk(){
System.out.println(" Father likes milk ");
}
}
public class Son extends Father{
@Override
void drinkMilk() {
System.out.println(" My son likes milk ");
}
public static void main(String[] args) {
Father son = new Son();
son.drinkMilk();
}
}

Son Class inheritance Father class , And rewrite the parent class dringMilk() Method , The output shows that the son likes to drink milk . So what is the binding method above ?

The above binding method is called Dynamic binding , Because when you write Father son = new Son() When , The compiler doesn't know son Who does the object really refer to , Only when the program is running does it know , This son It's a Father Class object , But it points to Son References to , This concept is called polymorphism , So we can sort out the three principles of polymorphism :

  • Inherit

  • rewrite

  • The parent class reference points to the subclass object

in other words , stay Father son = new Son() , Trigger the dynamic binding mechanism .

The process of dynamic binding

  1. Method table for virtual machine to extract the actual types of objects ;
  2. Virtual machine search method signature ;
  3. Calling method .

The characteristics of dynamic binding and static binding

Static binding

Static binding triggers at compile time , So its main feature is

1、 Compile time trigger , Be able to know code errors in advance

2、 Improve the efficiency of program operation

Dynamic binding

1、 The prerequisites for using dynamic binding can improve the usability of your code , Make the code more flexible .

2、 Polymorphism is the basis of design patterns , Can reduce coupling .

Java What are the grammar sugar in

Grammatical sugar refers to some kind of grammar added to computer language , This grammar has no effect on the function of language , But it's easier for programmers to use . because Java Code needs to run in JVM in ,JVM It doesn't support grammatical sugar , Syntax sugar will be reduced to a simple basic syntax structure in the program compilation phase , This process is Paraphrase sugar .

I'll list them below Java What are the grammar sugar in

  • Generic : Generics are grammatical sugars . stay JDK1.5 in , Introduced generic mechanism , But the generic mechanism itself is through Type Erasure To achieve , stay JVM There are no generics in , There are only common types and common methods , Type parameters of generic classes , Will be erased at compile time .

  • Automatic unpacking and packing : Automatic unpacking and automatic packing is a kind of grammatical sugar , It's about automatic conversion between wrapper classes of eight basic data types and their basic data types . To put it simply , Boxing is the automatic conversion of basic data types to Wrappers type ; Unpacking is automatically converting the wrapper type to the basic data type .

  • Inner class : The inner class is also a grammar sugar , Because it's just a compile time concept , Once the compilation is complete , The compiler will generate a separate class file , be known as outer$innter.class.

  • Variable length parameter : Variable length parameter is also a relatively small usage , So called variable length parameter , That is, the method can accept parameters with indefinite length . In general, we will not use variable length parameters in development , And variable length parameters are not recommended , It can make our programs harder to handle .

  • enhance for loop : enhance for Circular and ordinary for Cycle comparison , More powerful and simpler code , You don't need to know the number of iterations and the index of the array to traverse ; enhance for The object of the loop is either an array , Or it's done Iterable Interface . This syntax sugar is mainly used to traverse arrays or collections , It can't change the size of the set during the loop .

  • Switch Support string and enumeration :switch Keyword native can only support Integers type . If switch And then String Type words , The compiler will convert it to String Of hashCode Value , So actually switch The grammar compares String Of hashCode .

  • Conditional compilation : In general , All the lines in the source program are compiled . But sometimes you want to compile part of the content only when certain conditions are met , That is, to specify compilation conditions for some content , This is it. Conditional compilation (conditional compile).

  • Assertion : It's called assert keyword , yes jdk 1.4 New features added after . It's mainly used during code development and testing , Used to judge some key data , If the key data is not what your program expects , The program warns or exits .

  • try-with-resources :JDK 1.7 Start ,java Introduced try-with-resources Statement , take try-catch-finally Simplified as try-catch, This is actually a Grammatical sugar , It is converted to try-catch-finally sentence . The new statement contains three parts :try-with-resources Statement 、try block 、catch block . It requires that try-with-resources The variables defined in the declaration implement AutoCloseable Interface , In this way, the system can automatically call their close Method , Instead of finally The function of closing resources in .

  • String addition : This must be known to all , There are two kinds of string splicing , If you can determine the result of the splice at compile time , So use + The concatenated string is optimized by the compiler directly to the result of addition , If the compile time cannot determine the result of the splice , The bottom layer will use StringBuilder Of append Splicing

In depth understanding of Java Grammatical sugar , You can refer to this article Java Grammar sugar in , Really sweet .

List and Set Similarities and differences

It's a cliche too .

The same thing

Java There are three types in the collection , Namely List、Set and Map, They are all located in java.util It's a bag , And it's all interfaces , They have their own implementation classes .

List The implementation classes of are ArrayList、LinkedList、Vector、CopyOnWriteArrayList etc.

Set The implementation classes of are HashSet、TreeSet、LinkedHashSet、SortedSet etc.

They also have their own abstract classes ,List The abstract class for is AbstractList、Set The abstract class for is AbstractSet. Abstract classes are mainly used as top-level interfaces, that is List、Set The development of this kind of interface , It implements some top-level interface functions and defines some template methods , This uses the template design pattern .

List and Set All inherited Collection Interface , All belong to one kind aggregate .

Now let's talk about List and Set The difference between

Difference

Orderliness

List It means a kind of Ordered set , in other words ,List The elements in are arranged in order ,List Interface can accurately control the insertion order of each element , You can find elements by index .

Set There is no requirement for the order of the set , Different implementation classes can define their own order , such as HashSet It's a kind of unordered data structure ,HashSet The elements in are out of order ;TreeSet The elements are sorted in their natural order ;LinkedHashSet It will be inserted according to the Set Sort the elements in order ;SortedSet Will be based on Comparable perhaps Comparator Sort in the order of comparison , In other words, you can customize the collation .

Is the element repeated

List Allow duplicate elements , also List Can be inserted null Elements , and Set Duplicate elements are not allowed , therefore Set Only one is allowed null Elements exist .

Tell me what you know Map

Map It's also a collection class that we use frequently in our daily development .

Map It's a support key-value That is to say Key value pair Stored objects . among , Key objects are not allowed to repeat , And the value object can repeat , And the value object can also be Map Type of , Just as elements in an array can also be arrays .

Map The implementation classes of the interface are :HashMap、TreeMap、LinkedHashMap class .

HashMap It's the most common Map Realized ,HashMap The underlying structure of the system is Array + Linked list , It will be based on key Of hashCode Value store data , have access to get(key) To get the value of the key ,HashMap It's not a thread safe container , And only one is allowed null Key value pair . stay HashMap When there are few elements in it ,HashMap It stores elements in the form of linked lists , When the amount of data reaches a certain level , The linked list will be turned into a red black tree for storage .

TreeMap It's a red black tree Map, It sorts the keys in the specified order ,TreeMap It's not thread safe Map,TreeMap Not allowed in null value , Otherwise, a null pointer exception will be thrown .

LinkedHashMap Ensures the insertion order of elements , In query traversal, the HashMap slow , It's also not a thread safe container .LinkedHashMap Empty elements can be allowed .

It is worth noting that ,Map There are still many problems to be solved Hashtable and ConcurrentHashMap, Both elements are thread safe Map.

Hashtable We don't usually use , Because its thread safety only uses simple violence synchronized Synchronization lock , Synchronization lock costs a lot , It is not recommended to use .

And the last one is ConcurrentHashMap 了 ,ConcurrentHashMap Is a high concurrency based on Multithreading Map, It's often used in multithreaded scenarios ,ConcurrentHashMap The bottom layer of is using Section lock , Segment lock locks each segment , While ensuring thread safety, lock granularity is reduced .

ArrayList 、LinkedList and Vector The difference between

ArrayList Is the implementation of a dynamic array based data structure ,LinkedList Data structures based on linked lists .

For random access get and set operation ,ArrayList Is better than LinkedList, because LinkedList To move the pointer .

For new and delete operations add and remove,LinedList predominance , because ArrayList To move data .

ArrayList and LinkedList It's not easy to be thread safe , They all need to be locked manually , Or use Collections Implementation of thread safety in Collections.synchronizedList To construct the . They all have fail-fast Research on fast failure mechanism .

This time may also ask you and me Vector The difference between

There are two main differences : Thread security and expansion

Vector And ArrayList equally , It's also implemented through arrays , The difference is that it supports threads Sync , That is, only one thread can write at a certain time Vector, Avoid inconsistency caused by multithreading writing at the same time , But synchronization is expensive , therefore , To visit it is better than to visit ArrayList slow .

When Vector or ArrayList When the element in exceeds its initial size ,Vector Will double its capacity , and ArrayList Only increase 50% Size . such ,ArrayList It's good for saving memory space .

Collections.sort and Arrays.sort Implementation principle of

Let's show it first Collections.sort and Arrays.sort Source code

You can see from these three pieces of code ,Collections.sort The final call is Arrays.sort The method in , that Collections.sort Without looking at the , Look directly at Arrays.sort that will do .

Arrays.sort There are three branches in the source code , If no external is provided Comparator Comparator words , Will call directly sort Method , After calling sort The method is as follows

First of all LegacyMergeSort.userRequested The judgment of the , So what does this judgment mean ?

It's like this , stay JDK1.6 Is used in LegacyMergeSort, stay JDK1.7 Is used in TimeSort, If you want to use the original LegacyMergeSort Words , You need to add... To the system variables

-Djava.util.Arrays.useLegacyMergeSort=true

This configuration .

If you don't use this configuration , The default call is ComparableTimSort.sort Method , This is actually a TimSort The optimization of the , and TimSort The sorting algorithm is Merge sort .

We from Arrays.sort You can see this from the second judgment in ,ComparableTimSort and TimSort The biggest difference is whether you provide an external comparator .

Iterator and ListIterator What's the difference?

We use... In our daily development process Iterator Use a lot of ,ListIterator Little contact , This question is mainly about your understanding of English List Familiarity with source code and knowledge of fail-fast Do you understand the mechanism .

In general ,Iterator and ListIterator The main difference is

  • Iterator In the process of traversing , You cannot modify the number of elements in the collection , Otherwise, an exception will be thrown .

  • The range of use is different ,Iterator Can be used in all collections , and ListIterator Can only be used in List Types and subtypes

  • listIterator Yes add Method , You can add elements to the collection , and iterator You can't .

  • listiterator and iterator There are hasnext and next Method can traverse elements in order , however listiterator Yes hasprevious and previous Method , You can traverse elements backwards

  • listiterator Can locate the current index location nextIndex and previousIndex Can achieve ,iterator No such function

  • listiterator You can modify objects set() Method can be implemented ,iterator Can only traverse , Do not modify .

say ArrayList Capacity expansion mechanism of

The interviewer asked you again today ArrayList The expansion mechanism of ...... Let's look at the source code

When will the capacity be expanded , It must have called add Method to add elements

ArrayList Adding elements makes a judgment , This is also ensureCapacityInternal How to do things , That is to say, it is a way to judge and determine the capacity , Let's go straight in

This method makes a judgment , We've got the notes on it , That's to say, you are the one ArrayList Whether the initial capacity is specified during construction , If List No elements in , It will take your initial capacity and ArrayList The judgment of the maximum capacity in the network , Whichever is larger .

And then call ensureExplicitCapacity Method , Determine whether capacity expansion is needed

You can see , If at this time ArrayList Of array elements size Larger than the stored elements , Will call grow Method , This grow The method is actually the expansion method .

This code is ArrayList Expansion mechanism . Let's analyze

First of all, I will get ArrayList Number of elements , And then put ArrayList Capacity expansion of 50%, Compare the expanded capacity with the parameter capacity , If it's smaller than the parameter , Take a larger capacity to copy elements . If the capacity ratio after expansion ArrayList The maximum capacity of , The maximum capacity will be determined

hugeCapacity Method to first determine whether the parameter is less than 0 , If it is, it will throw out OutOfMemoryError abnormal , If not, judge the parameters and ArrayList Who is the biggest capacity , If the parameter is large , The value will be Integer.MAX_VALUE, If it is small, it will be taken MAX_ARRAY_SIZE.

BIO、NIO、AIO The difference between

Simply speaking ,BIO(Blocking I/O), It's a synchronous blocking IO, Data reading and writing must be completed in one thread , That is to say, it has only one execution sequence flow , If you encounter IO Read operation of stream , It has to wait IO After reading or writing the stream , Then we can do the next work .

NIO(non-blocking IO) It's also called new io, It is JDK 1.4 A new addition to the above version IO flow , It's a synchronous non blocking IO Model . stay NIO in , The thread will return immediately after it initiates the request , Synchronization means having to wait IO The data in the buffer is ready , Instead of blocking, it means , The user thread does not wait in place IO buffer , You can do something else first , But it's time to poll and check IO Whether the buffer data is ready .Java in Of NIO yes new IO It means . It's actually NIO add IO Multiplexing technology . ordinary NIO It's thread polling to see a IO Whether the buffer is ready , and Java Medium new IO A thread polling to see a bunch of IO Which of the buffers are ready , This is a kind of IO The idea of multiplexing .IO In multiplexing model , Will check IO The task of data readiness , Give it to the system level select or epoll Model , It's monitored by the system , Reduce the burden of user threads .

AIO It's really asynchronous, non blocking IO Model . Above NIO In the implementation , Need user thread to poll regularly , Go check IO Whether the buffer data is ready , Using application thread resources , In fact, polling is equivalent to blocking , Not really freeing the current thread , Because it still needs to query which IO be ready . And the real ideal asynchronous non blocking IO The kernel system should be allowed to complete , The user thread just needs to tell the kernel , When the buffer is ready , Notify me or execute the callback function I give you .

The difference between deep copy and shallow copy

stay Java in , Depending on how much you copy the object's properties ( Basic data classes and reference types ), It can be divided into two types :

  • Shallow copy Shallow Copy
  • Deep copy Deep Copy

Shallow copy : Shallow copy will recreate an object , This object has a copy of the original object property value . If the attribute is a basic type , The copied values are the basic types ; If the property is a memory address ( Reference type ), Copy is the memory address , So if one of the objects changes the address , It will affect another object . That is to say, the default copy constructor only makes a shallow copy of the object , That is, copy one member by one , That is, copy only object space, not resources .

Implement shallow copy , Need to achieve Cloneable Interface , And overwrite clone() Method .

Deep copy : For member objects of basic data types , Because the underlying data type is value passing , So it's directly assigning property values to new objects . Copy of base type , One of the objects modifies the value , It won't affect the other ( Just like a shallow copy ). For reference types , Such as arrays or class objects , Deep copy will create a new object space , Then copy the contents , So they point to different memory spaces . Change one of them , It won't affect the other one . For objects with multiple layers , Every object needs to implement Cloneable And rewrite clone() Method , And then realize the serial layer by layer copy of the object . Deep copy is slower and more expensive than shallow copy .

Java Five ways to create objects

Java There are five ways to create objects

  1. Use new To create objects
Object obj = new Object();
  1. Use newInstance Method to create
User user = (User)Class.forName("com.cxuan.test.User").newInstance();
// Or use
User user = User.class.newInstance();
  1. Use reflection to create objects
Constructor<User> constructor = User.class.getConstructor();
User user = constructor.newInstance();
  1. Using object clones to create objects
Constructor<User> constructor = User.class.getConstructor();
User user = constructor.newInstance();
user.setName("cxuan");
User user2 = (User)user.clone();
System.out.println(user2.getName());
  1. Using deserialization to create objects
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("xxx"));
out.writeObject(user2);
out.close();
//Deserialization
ObjectInputStream in = new ObjectInputStream(new FileInputStream("xxx"));
User user3 = (User) in.readObject();
in.close();
user3.setName("cxuan003");
System.out.println(user3 + ", hashcode : " + user3.hashCode());

Learn more about these ways of creating objects , You can refer to Inventory Java Create the object's n Kind of operation

trivia

This article has been written for a long time , The official account of WeChat is 3w word ,31 Pictures , Reading time is about 77 minute .

I know this reading time can take the subway 10 The No.1 line has gone round Beijing , There will also be a lot of people who are disgusted , The article is so long , Who has time to watch it ? I've heard this fast food question countless times , But every time I turn a deaf ear . Yeah , We do it every day , Tiktok , Make headlines and watch beautiful women , Brush the official account to see a group of big guys fucking great , Then he scolded :" Oh my god , What a waste 1 Hours ", Then he pretended to be serious 15 Minute code , Continue to waste .

I know this article is still not read by many people , Because it's going to be inundated with information , Maybe you'll put it in your favorites when you finish reading it , Even you think I wrote Pediatrics , Maybe this article won't make a ripple in your programming career , I don't want to describe a phenomenon too much . I'll just say what I've done . Probably not in this article 20 Links , Among them is 14 All the articles are the contents of my official account .

A different piece of String、StringBuffer、StringBuilder Detailed explanation

A little static It's hard to live in me ?

After reading this HashMap , It's OK to argue with the interviewer

After reading this Exception and Error , It's OK to argue with the interviewer

Deep understanding of dynamic agent

Dynamic proxy is so simple !

In depth understanding of IO

I explained the singleton model to the interviewer , He gave me a thumbs up

Comparable and Comparator The understanding of the

After learning to reflect , I was admitted to !( dried food )

Deep understanding of various citation issues

After reading this final、finally and finalize It's OK to argue with the interviewer

Java Grammar sugar in , Really sweet .

Inventory Java Create the object's n Kind of operation

I think , It's good for me github https://github.com/crisxuan/bestJavaer What's said above .

Okay , That's it , As for what do you like to watch , Just feel free , I hope this article can help you .

I've got six of them myself PDF, WeChat search 「 The programmer cxuan」 After the official account , Reply in the background cxuan , Collect all PDF, these PDF as follows

Six PDF link

版权声明
本文为[Programmer]所创,转载请带上原文链接,感谢
https://javamana.com/2021/04/20210408104919026b.html

  1. Java 学生成绩管理系统课程设计,附源码!
  2. Java arbitrary audio to MP3
  3. DNS of docker
  4. Docker - build log monitoring system
  5. SSM + MySQL + Maven + Shiro WMS
  6. Top 10 reasons to fall in love with java!
  7. 一本关于HTTP的恋爱日记
  8. 【RocketMQ源码分析】深入消息存储(3)
  9. SpringCloud+Nacos实现服务配置中心(Hoxton版本)
  10. SCIP:构造数据抽象--数据结构中队列与树的解释
  11. SCIP:构造过程抽象--面向对象的解释
  12. 使用 docker 进行 ElasticSearch + Kibana 集群搭建
  13. Spring IOC 特性有哪些,不会读不懂源码!
  14. [DB Bao 41] use of PMM -- monitoring mysql, PG, mongodb, proxysql, etc
  15. Spring Cloud 升级之路 - 2020.0.x - 3. Undertow 的 accesslog 配置
  16. [DB Bao 42] MySQL high availability architecture MHA + proxysql realizes read-write separation and load balancing
  17. [DataGuard] recovery of physical DG in case of losing archive files in main database (7)
  18. MyBatis(3)Map和模糊查询拓展
  19. 【TTS】AIX-&gt;Linux--基于RMAN(真实环境)
  20. 【TTS】传输表空间AIX-&gt;linux基于rman
  21. 【TTS】传输表空间AIX asm -&gt; linux asm
  22. 【TTS】传输表空间Linux asm -&gt; AIX asm
  23. 【DB宝40】MySQL高可用管理工具Orchestrator简介及测试
  24. 【TTS】传输表空间Linux -&gt;AIX 基于rman
  25. 一本关于HTTP的恋爱日记
  26. 【RocketMQ源码分析】深入消息存储(3)
  27. SpringCloud+Nacos实现服务配置中心(Hoxton版本)
  28. SICP:构造过程抽象--面向对象的解释
  29. 3w 字长文爆肝 Java 基础面试题!太顶了!!!
  30. Spring Cloud 升级之路 - 2020.0.x - 3. Undertow 的 accesslog 配置
  31. win10卸载mysql5.7
  32. MySQL 批量插入,如何不插入重复数据?
  33. k8s cronjob应用示例
  34. 非常规方法,轻松应对Oracle数据库危急异常
  35. Oracle hang 之sqlplus -prelim使用方法
  36. 如何全文搜索oracle官方文档
  37. Java student achievement management system course design, with source code!
  38. win10安装mysql8.0
  39. 手把手教你写一个spring IOC容器
  40. JAVA 中的异常(1)- 基本概念
  41. A love diary about http
  42. navicat连接win10 mysql8.0 报错2059
  43. [rocketmq source code analysis] in depth message storage (3)
  44. Implementation of service configuration center with spring cloud + Nacos (Hoxton version)
  45. SCIP: constructing data abstraction -- Explanation of queue and tree in data structure
  46. SCIP: abstraction of construction process -- object oriented explanation
  47. Using docker to build elasticsearch + kibana cluster
  48. What are the spring IOC features? I can't understand the source code!
  49. Spring cloud upgrade road - 2020.0. X - 3. Accesslog configuration of undertow
  50. 导致Oracle性能抖动的参数提醒
  51. 风险提醒之Oracle RAC高可用失效
  52. 小机上运行Oracle需要注意的进程调度bug
  53. Oracle内存过度消耗风险提醒
  54. Oracle SQL monitor
  55. 使用Bifrost实现Mysql的数据同步
  56. 揭秘Oracle数据库truncate原理
  57. 看了此文,Oracle SQL优化文章不必再看!
  58. Mybatis (3) map and fuzzy query expansion
  59. Kafka性能篇:为何这么“快”?
  60. 两个高频设计类面试题:如何设计HashMap和线程池