Advanced java interview questions with full answers based on a compilation Huawei 2020 (complete and detailed version)

Advanced java interview questions with full answers based on a compilation Huawei 2020 (complete and detailed version)

java-based and more "comparative"

 

I learned the details point

1.Collections.sort internal sorting principle

Used in Java 6 in Arrays.sort () and Collections.sort () is MergeSort, while in Java 7, the internal implementations replaced TimSort, its implementation requirements more stringent comparison between objects

2.hashMap principle, java8 do change

In terms of the structure to achieve, HashMap list is an array + + red-black tree (JDK1.8 increased red-black tree part) realized. HashMap key allows a maximum of one record is null, allowing more than one record is null. HashMap non-thread-safe. ConcurrentHashMap thread safe. Collision solution: when a conflict occurs, using the fastener method, the keyword synonyms of nodes linked in a single linked list, the hash table length m, defines a pointer array T m of pointers to the head address of the node i insertion point to T (i) is a single-head pointer list. Java8, the collision exceeds the limit element (8), replacing the list with the red-black tree.

The difference 3.String and StringBuilder

1) variable and non-variable: String immutable, each execution of the "+" new situation will create a new object, without frequent changes in the string String, to save memory.

2) whether the multi-thread safe: StringBuilder and no method plus genlock, so not thread-safe. String and StringBuffer are thread-safe.

Array with the difference 4.Vector

1) The default is the ArrayList extensions 50% + 1 when memory is insufficient, Vector is the default extension 1 fold.

2) Vector belong thread safe level, but do not use Vector most cases, because of the need for greater security thread overhead.

5.HashMap the difference between Hashtable

1) historical reasons: Hashtable inherited Dictonary class, HashMap inherited from abstractMap

2) HashMap allows null key-value pairs, but only up to a null object, and HashTable is not allowed.

3) HashTable synchronized, and HashMap non-synchronized, the efficiency is higher than the HashTable

6.ConncurrentHashMap and hashtable compare (two threads concurrently access the map, delete a thread at the end of the same strand, a thread traversing look ahead, asking why the previous thread but also the right to find the back of the node to be deleted by another thread )

ConcurrentHashMap combines the advantages of both hashtable hashmap. hashtable is doing a synchronized, that is thread-safe, hashmap not consider synchronization. So hashmap in the case of single-threaded high efficiency. In the next hashtable multithreading, synchronization operations to ensure the correctness of program execution. But hashtable is blocked, must be performed each time synchronization lock the entire structure, ConcurrentHashMap precisely in order to solve this problem born,

ConcurrentHashMap concurrently allowing multiple modifications, which lock key is used separation technique (Array save a plurality Object, use these objects as separate lock latch, get / put to use any of a random). It uses a plurality of locks to control different parts of the hash table modifications performed. In JDK 1.6, there exist HashEntry structure, inserting each time a new node is added as the head node chain (HashMap achieve the same), and each time a deleted nodes, all copies will be deleted prior to a formation of a new node chain, whereas the current node a next node point to the next current node, so there are two strands are present in later removed, it is possible to ensure that even in the same chain, deleting a thread, and the other thread traversal, they can work well, because traversing thread can continue to use the original chain.

Java8, the use of volatile HashEntry stored data, as a lock element table; + singly linked list arrays from the table together with the red-black tree. Red-black tree is a binary search tree special characteristics are: 1. Node red or black black root node 2. 3. 4. A leaf node is a black node is red, then the leaf node is a black 5 node to which the same number of nodes on all paths black descendants nodes.

The difference 7.ArrayList and LinkedList?

The most obvious difference is

ArrrayList the underlying data structure is an array, it supports random access, the underlying data structure LinkedList book list, does not support random access. Subscript an element, ArrayList time complexity is O (1), while LinkedList is O (n). LinkedList is a doubly linked list

8.Java in, Comparator and Comparable What is the difference?

Comparable natural ordering interface defines the object, the interface is ordered, the comparator commonly used to define custom order is more interfaces. If we need to control the order of a class, but the class itself does not support ordering (ie not implement the Comparable interface), then we can build a "class Comparator" to sort. Comparable always only one, but there may be multiple comparator order to define the object.

9. What is the abstract class? It is the interface What is the difference? Why do you want to use too abstract class?

An abstract class means not allowed to be instantiated class; a class can only be used once inheritance. However, a class but can implement multiple interface.

Different abstract class and interface design reflects the idea. In fact, the abstract class is the "is-a" relationship, interface represents the "like-a" relationship

Abstract classes and implement interfaces for all of these methods must be implemented. The method can have non-abstract in the abstract class. There can not be an interface realization. But in Java8 interface allows static default method.

Variables defined in an interface default public static final type, and must for its initial value, so that the class can not be redefined to achieve, nor change its value. Abstract class default friendly type variable, whose value can be redefined in subclasses may be reassigned.

Abstract subclass implementing the method of the parent class, the visibility may be greater than equal to the parent class; the interface class interface methods in visibility only the same interface (public).

Abstract class is used for reuse. Reduce the amount of coding, to reduce coupling.

I learned the details point

10. Description of overloading and rewrite in Java?

Overloading and rewrite allow you to use the same name for different functions, but overloading is a compile-time activities, and rewriting is active runtime. You can override methods, but can only override methods in a subclass in the same class. Rewrite must have inherited

Rewriting: 1, in a subclass can be rewritten to the methods inherited from the base class to needed. 2, a method override method is overridden and must have the same method name, return type and parameter list. 3, can not use the overridden method is more stringent than the methods are overridden access.

When overloaded, the method name to be the same, but not the same number and type of parameters, return type may be the same or different. Unable to return typed overloaded function as a distinguishing criterion.

What is the difference 11.Collection and Collections are?

Collection is a set of Java framework basic interface;

Collections is a tool framework provides a set of Java class, which contains a large number of static methods for collection or return operation.

The principle of polymorphism in 12.Java

The so-called polymorphisms, refers to the parent class reference point to a subclass object invokes achieve implementation subclass rather than the parent class method call. Implementation polymorphism key is "dynamic binding."

In 13.object defines which method?

clone(), equals(), hashCode(), toString(), notify(), notifyAll(),

wait(), finalize(), getClass()

14.Java generics and type erasure?

That generic parameterized type, when you create a collection, a collection of elements of the specified type, this collection can only be passed in this type of argument. Type erasure: java byte code generated by the compiler does not contain generic information, erasing at compile time: 1 with the most generic top-level parent replacement; 2 removed.

15. say five new features introduced in JDK 1.8?

Java 8 is a history in the Java open up new versions of JDK 8 in the following five main features:

Lambda expressions; allow anonymous function like an object passing Stream API, take full advantage of modern multi-core CPU, you can write a very simple code; Date and Time API, finally, there is a stable and simple date and time you use extended library available the method, now, the interfaces may be static, the default method; repeated notes, now you can use the same comment multiple times on the same type.

16.java in public, private, protected, and default keywords range visit:

Protected within the package and the package can be accessed like my husband, default can only be accessed within the same package, prvate only the same type of

17. The common data structures:

Set of linear structure (an array, queues, linked lists, and stacks), tree structure, like the structure of FIG.

The 18.Java TreeMap is the use of what the tree achieved? (answer)

TreeMap is the use of Java in the red-black tree implementation.

19. What is an anonymous inner classes? How to access variables outside of its definition?

Anonymous inner classes is the name of the internal classes, anonymous inner classes can only be used once, it is usually used to simplify writing code.

Final anonymous inner classes can only access the external variable like Java 8 more intelligent: If the local variable is accessed anonymous inner class, then the local variable is equivalent to automatically use the final modification.

20. How to create a singleton? He said a double check, he said, is not thread safe. How to efficiently create a thread-safe singleton?

One is by enumerating, one is static inner classes.

() Method and the difference between 21.poll remove () method?

poll () and

remove () are removed from a queue element, but poll () Gets the element at the time of failure will return empty, but remove () will throw an exception on failure.

22. Write code to remove an element when traversing ArrayList

Using an iterator.

Iterator itr = list.iterator();

while(itr.hasNext()) {if(…) { itr.remove();} }

JVM

1.JVM how loading a class, parents delegate in what ways the model

 

I learned the details point

Class loading process: loading, verification (verification stage role is to ensure the information contained in the file byte stream Class meets JVM specification, will not cause harm to the JVM), preparation (preparation phase for the variable allocate memory and set the class variable initialization), parsing (parsing the constant pool is replaced by a direct reference symbolic reference), initialization.

Parent delegation model method: parents delegate refers to a class if the class received a request to load, not their first attempt to load, go first to the parent class loader to complete. When the top-level boot loader represents the class time can not load this class, sub-class will attempt to load their own. Back to the open when the initiator of the loader can not load, it is not looking down, but an exception is thrown ClassNotFound.

Method: Start (on Bootstrap) class loader, standard extended (the Extension) class loader application class loader (the Application), the context (the Custom) class loader. Meaning is to prevent multiple copies of the same memory byte code appears.

2.GC algorithm (what kind of objects considered recyclable objects, reachability analysis), CMS collector

Jvm is how to determine an object has become recyclable "rubbish", generally two methods: reference notation and root search algorithm. Reference notation is no way to solve the problem of circular references, so the search by roots. From a series of "GC Roots" objects down to start the search, called search path traversed by the chain of references. When an object is no reference to the link between the "GC Roots", it referred to as reference unreachable. A reference to the object can not be considered recyclable objects.

Some garbage collector: 1, Serial New / Serial Old (serial), 2, Parrallel New (parallel), 3, Parrallel Scavenge, 4, Parrallel Old, 5, CMS (CMS collector is a pause in order to obtain the shortest recovery time objectives collector, which is a concurrent collector, using the Mark-sweep algorithm.), 6, G1 (concurrent is a parallel with the collector, and the dwell time may be established model prediction, whole cleaning is based on the marking, using a partial copy)

3.JVM which is divided into zones, each zone of why?

1) the method area (method): is shared by all threads. The method area contains all the information about the classes and static variables.

2) heap (heap): shared by all threads, as well as an array of storage object instance, Java heap is the main area of ​​the GC.

3) the stack (stack): Each thread contains a stack area, saving some of the local stack variables.

4) Program Counter: the row is the current thread pointer bytecode execution.

4.JVM the new generation, the old era, lasting generations, what things are stored?

Permanent generation is stored in the main class information Java classes, not Java object-relational and garbage collection to be collected. First of all newly created objects are placed on the young generation and the old generation are stored in some of the longer life cycle of the object.

The memory overflow and memory leak:

Out of memory: memory when the application program, there is not enough memory, out of memory; memory leak value can not be recycled garbage objects, you can use memory analyzer tool to view leak.

6. processes and threads:

Process values ​​running program (independence, dynamic, concurrency), the thread refers to the process of implementation of the order flow. The difference is: 1 does not share memory between processes 2. Create the cost of resource allocation processes were much larger, multi-threaded so in highly concurrent environments with high efficiency.

7. serialization and deserialization:

Serialization refers to java objects into a sequence of bytes, opposite deserialization. Java mainly to inter-thread communication, to achieve the object passed. Only Externalizable interface implements the Serializable class object or before being serialized.

8.64 JVM, int length is the majority?

Java, int type variable length is a fixed value, regardless of the platform, are 32-bit. That means, in 32-bit and 64-bit Java virtual machine, int type is the same length.

9.Java in WeakReference and SoftReference difference?

Java in a total of four types of reference. StrongReference, SoftReference, WeakReference and PhantomReference.

GC will be recovered StrongReference is the default reference implementation of Java, it will survive as long as possible in the JVM, when there are no objects to it when

WeakReference, the name implies, is a weak reference, when an object is referenced in

When the JVM is no longer strong references will be recovered GC

Although WeakReference and SoftReference are conducive to improving the efficiency of GC and memory, but WeakReference, once lost the last strong reference, GC will be recycled, while SoftReference will be retained as long as possible until the reference will be recycled out of memory when the JVM (Virtual machine guarantees), so that this feature

SoftReference very suitable for application cache

10. The interpretation of Java heap space and GC?

When you start the Java command

When Java process will allocate memory for it. A portion of memory space for creating a heap, when an object is created in the program, it allocates memory for the space. GC is a process within the JVM, invalid objects recovered memory for future allocation.

11.Java heap and stack What is the difference?

The JVM heap and stack belong to different memory areas, the use of different purposes. Preservation methods commonly used in the frame stack and local variables, and the object is always allocated on the heap. Heap stack is usually relatively small, it will not be shared among multiple threads, the heap is shared by all threads across the JVM.

Concurrency, locks

1.volatile keyword, Lock

Concurrent programming: atomicity issues, the visibility problem, ordering problem.

volatile keyword can ensure visibility, it can prohibit the instruction word reordering, but can not guarantee atomicity. Visibility can only guarantee that every reading is current value, but no way to guarantee the volatile atomic operations on variables. Lock adding keywords and become a memory barrier in the statement generated.

Lock implementations provide than using synchronized methods and statements available to a wider range of lock operation, it can in a more elegant way to handle thread synchronization issues. With sychronized modified method or block of statements after the code executing the automatic lock release, and we need to use the manual release lock Lock

2.MYSQL common optimization (sql optimization, optimizing the structure of the table)

SQL optimization, table mechanism optimization, index optimization, parameter optimization cache

3.java every change that need to be recompiled deployment package, there is no better way

You can use the thermal load

I learned the details point

4. What are the inter-process communication ways?

1)管道(Pipe),2)命名管道(named pipe),3)信号(Signal),4)消息(Message)队列,5)共享内存,6)内存映射(mapped memory),7)信号量(semaphore),8)套接口(Socket)

5.Sychronized修饰静态方法,锁定类本身而不是实例,非静态方法锁定实例。

6. 操作系统什么情况下会死锁?

所谓死锁:是指多个进程在运行过程中因争夺资源而造成的一种僵局。产生的原因:竞争资源:当系统中多个进程使用共享资源,并且资源不足以满足需要,会引起进程对资源的竞争而产生死锁。进程间推进的顺序非法:请求和释放资源的顺序不当,也同样会导致产生进程死锁

7.产生死锁的四个条件:

1.互斥条件(进程独占资源)2.请求与保持(进程因请求资源而阻塞时,对已获得的资源保持不放) 3.不剥夺条件(进程已获得的资源,在末使用完之前,不能强行剥夺) 4.循环等待(若干进程之间形成一种头尾相接的循环等待资源关系)

8. 如何理解分布式锁?

由于在平时的工作中,线上服务器是分布式多台部署的,经常会面临解决分布式场景下数据一致性的问题,那么就要利用分布式锁来解决这些问题。

9. 线程同步与阻塞的关系?同步一定阻塞吗?阻塞一定同步吗?

线程同步与否 跟 阻塞非阻塞没关系,同步是个过程,阻塞是线程的一种状态。多个线程操作共享变量时可能会出现竞争。这时需要同步来防止两个以上的线程同时进入临界区内,在这个过程中后进入临界区的线程将阻塞,等待先进入的线程走出临界区。

10. 同步和异步有什么区别?

同步和异步最大的区别就在于。一个需要等待,一个不需要等待。同步可以避免出现死锁,读脏数据的发生,一般共享某一资源的时候用,如果每个人都有修改权限,同时修改一个文件,有可能使一个人读取另一个人已经删除的内容,就会出错,同步就会按顺序来修改。

11. 线程池

根据系统自身的环境情况,有效的限制执行线程的数量,使得运行效果达到最佳。线程主要是通过控制执行的线程的数量,超出数量的线程排队等候,等待有任务执行完毕,再从队列最前面取出任务执行

12. 如何调用 wait()方法?使用 if 块还是循环?为什么?

wait() 方法应该在循环调用,因为当线程获取到 CPU 开始执行的时候,其他条件可能还没有满足,所以在处理前,循环检测条件是否满足会更好。

wait(),notify()和notifyall()方法是java.lang.Object类为线程提供的用于实现线程间通信的同步控制方法。等待或者唤醒

13. 实现线程的几种方法

(1)继承Thread类,重写run函数

(2)实现Runnable接口,重写run函数

(3)实现Callable接口,重写call函数

14. 什么是多线程环境下的伪共享(false sharing)?

伪共享是多线程系统(每个处理器有自己的局部缓存)中一个众所周知的性能问题。缓存系统中是以缓存行(cache line)为单位存储的。缓存行是2的整数幂个连续字节,一般为32-256个字节。最常见的缓存行大小是64个字节。当多线程修改互相独立的变量时,如果这些变量共享同一个缓存行,就会无意中影响彼此的性能,这就是伪共享。

网络、数据库

1.TCP如何保证可靠传输?三次握手过程?

在TCP的连接中,数据流必须以正确的顺序送达对方。TCP的可靠性是通过顺序编号和确认(ACK)来实现的。TCP 连接是通过三次握手进行初始化的。三次握手的目的是同步连接双方的序列号和确认号并交换 TCP 窗口大小信息。第一次是客户端发起连接;第二次表示服务器收到了客户端的请求;第三次表示客户端收到了服务器的反馈。

2. Linux下你常用的命令有哪些?

1. cd命令用来改变所在目录。cd / 转到根目录中cd ~ 转到用户目录下

2. ls命令用来查看目录的内容。

3. cp命令用来拷贝文件cp

4.mv命令 mv t.txt Document 把文件t.txt 移动到目录Document中。

3. 常用的hash算法有哪些?

1.加法hash:所谓的加法Hash就是把输入元素一个一个的加起来构成最后的结果。

2.位运算hash:这类型Hash函数通过利用各种位运算(常见的是移位和异或)来充分的混合输入元素

3.乘法hash:33*hash + key.charAt(i)

详细内容点我学

4. 什么是一致性哈希?

设计目标是为了解决因特网中的热点(Hot spot)问题,一致性hash算法提出了在动态变化的Cache环境中,判定哈希算法好坏的四个定义:1、平衡性(Balance) 2、单调性(Monotonicity) 3、分散性(Spread) 4、负载(Load)

5. 数据库中的范式有哪些?

第一范式—-数据库中的表(所有字段值)都是不可分割的原子数据项。

第二范式—-数据库表中的每一列都和主键相关,而不能只和主键的某一部分相关。

第三范式—-数据库表中每一列数据都和主键直接相关,不能间接相关。范式是为了减小数据冗余。

6. 数据库中的索引的结构?什么情况下适合建索引?

数据库中索引的结构是一种排序的数据结构,数据库索引是通过B树和变形的B+树实现的。什么情况下不适合建立索引:1.对于在查询过程中很少使用或参考的列;对于那些只有很少数据值的列;对于那些定义为image,text和bit数据类型的列;当修改性能远大于检索性能。

根据系统自身的环境情况,有效的限制执行线程的数量,使得运行效果达到最佳。线程主要是通过控制执行的线程的数量,超出数量的线程排队等候,等待有任务执行完毕,再从队列最前面取出任务执行

7. concurrent包下面,都用过什么?

java.util.concurrent、java.util.concurrent.atomic和java.util.concurrent.lock

8. 常用的数据库有哪些?redis用过吗?

9. 你知道的开源协议有哪些?

GPL (GNU General Public License) :GNU通用公共许可协议

LGPL (GNU Lesser General Public License) :GNU宽通用公共许可协议

BSD

(Berkeley Software Distribution) :伯克利软件分发许可协议

MIT (Massachusetts Institute of Technology):MIT之名源自麻省理工学院

Apache (Apache License) :Apache许可协议

MPL (Mozilla Public License) :Mozilla公共许可协议

10.表单提交中,get和post区别

1.get从服务器获取信息,post向服务器传信息

2.get传送数据量比较小,post可以比较大

3.get安全性比较低

11. TCP 协议与 UDP 协议有什么区别?(answer答案)

TCP(Tranfer Control Protocol)的缩写,是一种面向连接的保证传输的协议,在传输数据流前,双方会先建立一条虚拟的通信道。可以很少差错传输数据。

UDP(User DataGram Protocol)的缩写,是一种无连接的协议,使用UDP传输数据时,每个数据段都是一个独立的信息,包括完整的源地址和目的地,在网络上以任何可能的 路径传到目的地,因此,能否到达目的地,以及到达目的地的时间和内容的完整性都不能保证。

所以TCP必UDP多了建立连接的时间。相对UDP而言,TCP具有更高的安全性和可靠性。

TCP协议传输的大小不限制,一旦连接被建立,双方可以按照一定的格式传输大量的数据,而UDP是一个不可靠的协议,大小有限制,每次不能超过64K。

发布了89 篇原创文章 · 获赞 63 · 访问量 4万+

Guess you like

Origin blog.csdn.net/aa541505/article/details/104072672