2019 latest java interview questions and answers

List, Set, Map whether inherited from the Collection interface?

A: List, Set Shi, Map not. Map key-value mapping containers, and Set List with a clear distinction, the fragmented and stored Set of elements does not permit duplicates (mathematics set too), the container is a linear structure List for-value index case access elements.

Describes ArrayList, Vector, LinkedList storage performance and characteristics.

A: ArrayList and Vector data is stored using an array, the array element number is greater than the actual data is stored so as to increase and insert elements, which allow the element directly indexed by serial number, but to insert the element array elements involved in memory operations like move, so index data fast and slow insert data, methods of Vector are modified by the addition of synchronized, so Vector is thread-safe container, but the poor performance than ArrayList, and therefore has a legacy container in Java. LinkedList implemented using a doubly linked list is stored (in the memory by the associated reference memory cell scattered added together to form a linear structure can be indexed by serial number, which compared to a continuous chain storage array storage, memory utilization higher), indexed by serial number before the data needs to traverse to or after, but only before and after the record of this can insert the data item, the insertion speed. Vector belong legacy container (container earlier versions of Java provided in addition, Hashtable, Dictionary, BitSet, Stack, Properties are the legacy container), is no longer recommended, but due to the ArrayList and LinkedListed are non-thread-safe, If the scene with a container of experience operating multiple threads, you can synchronizedList methodological tools category Collections will convert it into thread-safe container before use (this is the application for decorating mode, existing objects will pass another the constructor of a class of objects to create a new enhancement implementation).

NOTE: Properties class vessel left and Stack classes have serious problems in the design, Properties is a special key and key values ​​are mapped string, the design should be associated with one and two which Hashtable generic type parameter is set to String, but in the Java API Properties directly inherited Hashtable, which obviously is the inheritance of abuse. Here multiplexing mode code should Has-A relationship instead of Is-A relationship, on the other hand containers are all tools, tools inherited class itself is a wrong approach, the best way to use tools is Has-A relationship (association) or Use-A relationship (dependency). Similarly, Stack class extends Vector is also incorrect. Sun's engineers have also made such a stupid mistake, people marvel.

Collection and Collections of the difference?

A: Collection is an interface, it is the parent interface Set, List and other containers; Collections is a utility class that provides a series of static methods to assist container operations, these methods include searching for containers, sorting, thread safety etc. Wait.

List, Map, Set when three interfaces to access elements, what are the differences?

A: List a particular index accesses elements, there may be duplicate elements. Set not store duplicate elements (with the object equals () method to distinguish whether to repeat elements). Map save key-value pair (key-value pair) mapping, mapping relationship can be one or many. When the container has Set Map implementation version based on two hash tree storage and sorting access time complexity is O (1) based on the theoretical version stored hash, the version of the tree sort Based insert or delete elements would constitute a sort tree in accordance with the key element or elements (key) and to re-ordering to achieve the effect.

TreeMap and TreeSet how to compare elements in the sort? How Collections utility class in sort () method to compare elements?

A: Class TreeSet object belongs storage requirements must implement the Comparable interface, which provides the comparison element compareTo () method, when the size of the insert elements will callback method comparison element. TreeMap key storage requirements on the key mapping must implement Comparable interface thereby sorted according to the key element. Collections sort method tools overloaded two forms, the first objects to be sorted requires incoming containers stored in Comparative implemented Comparable interface for comparing element; a second container elements is not a mandatory requirement must be compared, but expects to be passed a second parameter, the parameter is a sub-type (compare elements need to override the compare method of implementation), corresponding to a temporary collation comparator interface defined, in fact, element by comparing the size of the interface injection algorithms, but also the application of callback mode (Java support for functional programming).

Thread class sleep () wait methods and objects () method can allow a thread suspended, What's the difference?

A: sleep () method (sleep) is a thread class (Thread) static method, this method is called the current thread will suspend execution of the specified time, the opportunity will be executed (CPU) to give other threads, but the lock object remains, So will automatically resume after the end of the sleep time (the thread back to the ready state, please refer to the thread state transition diagram of the first 66 questions). wait () method of the Object class, call the object's wait () method causes the current thread to give up the object lock (thread suspended), enter the object wait pool (wait pool), only call the object's notify () method (or notifyAll to wake up threads waiting to enter the pool and other pools lock (lock pool) when () method), if the thread regain lock objects can enter the ready state.

Added: probably a lot of people on what is the process, what is the thread is still relatively vague, why the need for multi-threaded programming is not particularly understand. Simply put: A process is a program with a certain separate functions run on the activities of a data set, is an independent unit operating system for resource allocation and scheduling; thread is a physical process, the CPU scheduling and dispatch of basic the unit is smaller than the process of the basic unit can operate independently. Dividing scale smaller than the thread process, which makes the procedure complicated multithreading high; the process usually have separate memory during execution, and the memory can be shared between threads. The use of multi-threaded programming can often lead to better performance and user experience, but multi-threaded program is unfriendly to other programs, as it may take up more CPU resources. Of course, not thread the more, the better the performance of the program, because the scheduling and switching between threads will be a waste of CPU time. Nowadays it is fashionable Node.js on the use of single-threaded mode of asynchronous I / O's.

sleep (thread) method and the yield () method What is the difference?

A: 1, sleep () method does not consider other threads to run when the opportunity priority thread, so that will give the opportunity to the low priority thread to run; yield () method will only give the same priority or higher priority opportunity thread to run;

2, thread execution after sleep () method into the blocked (blocked) state, and after the implementation of yield () method into the ready (ready) state;

3, sleep () method declaration throws InterruptedException, while the yield () method does not declare any exceptions;

4, sleep () method is more portable than the yield () method (associated with the operating system, CPU scheduling).

When a thread enters a synchronized method A object, other threads can access synchronized method B of this object?
A: No. Asynchronous method other threads can access the object, it can not enter synchronization method. Because the synchronized modifier on a non-static method requires the execution method to obtain a lock object, if the method has entered A description of the object lock has been removed, then tried to enter the thread B method can only lock in the pool, etc. (note not wait Oh lock pool) waiting objects.

Please state synchronization with the thread and the thread scheduling related methods.

A: wait (): make a thread in waiting (blocked) state, and release the lock held by the object;

sleep (): make a running thread in a sleep state, is a static method, this method is called to handle InterruptedException anomaly;

notify (): wake up a thread in a wait state, of course, when this method is called, does not exactly wake up one thread wait state, but which is determined by the JVM thread wakes up, and regardless of priority;

notityAll (): wake up all the threads in a wait state, the method will not object to lock all the threads, but to let them compete, only a thread to acquire a lock to enter the ready state.

Tip: About Java multithreading and concurrent programming problems, I recommend you read my other article "Summary and Reflections on Java concurrent programming."

Supplementary: Java 5 interface provides explicit locking mechanism (explicit lock) through Lock, enhancing the flexibility and coordination of the thread. Lock interface defined in the lock (Lock ()) and unlocking (UNLOCK ()) method, while also providing newCondition () method to generate Condition objects for communication between threads; In addition, Java 5 also provides a signal the amount of mechanisms (semaphore), semaphores can be used to limit the number of accesses to a shared resource threads. Before access to a resource, a thread must obtain the semaphore permission (call Semaphore object acquire () method); after the completion of access to resources, the thread must return the license to the semaphore (call Semaphore object release () method) .

There are several writing multithreaded program implementation?

A: Java 5 previous multi-threading implemented in two ways: one is to inherit the Thread class; the other is to achieve Runnable interface. Must be defined in two ways by overriding thread run () method of behavior, it is recommended to use the latter, because in Java inheritance is single inheritance, a class has a parent class inherits the Thread class if you can not inherit from other classes , apparently using Runnable interface more flexible.

Supplementary: Java to create a thread after 5 there is a third way: to achieve Callable Interface, call methods on the interface can generate a return value at the end of the thread execution.

Use of synchronized keyword?

A: synchronized key may be labeled as an object or a method of synchronization to enable exclusive access to the objects and methods, can be synchronized (object) {...} define the synchronization code block, or when the synchronized statement method as a method of modifying symbol.

Illustrates a synchronous and asynchronous.

A: If there is a critical resource system (the number of resources is less than the number of threads of resource competition for resources), for example, may be read by another thread after the writing of data, or data is being read may have been written by another thread , then these data must be synchronized access (exclusive database lock operation is the best example). When the application calls the method takes a long time to execute on the object, and do not want the program to wait for the process to return, you should use asynchronous programming, using asynchronous approach in many cases tend to be more efficient. In fact, the so-called synchronization refers to the blocking operation, and is non-blocking asynchronous operation.

Start a thread that calls the run () or start () method?

A: Start a thread that calls start () method, the thread is represented by the virtual processor can run the state, which means that it can schedule and execute by the JVM, this does not mean that the thread will run immediately. run () method is a method to start a thread after a callback (callback) is.

What is the thread pool (thread pool)?

A: In object-oriented programming, creating and destroying objects is very time consuming, because an object is created to get more memory resources or other resources. Especially in Java virtual machine will attempt to track every object to make garbage collection after the object is destroyed. Therefore, to improve the efficiency of the service program is a means to minimize the number of creating and destroying objects, especially some very resource-intensive objects are created and destroyed, which is why "pooled resources" techniques. As the name suggests the thread pool is created in advance a number of executable threads into a pool (container), the time needed to obtain the thread from the pool do not create your own, do not need to be destroyed after use but the thread back into the pool, thereby reducing the creation and destruction overhead thread object.

  Java 5+ The Executor interface defines a thread of execution tool. It is a subtype that is the thread pool interface is a ExecutorService. To configure a thread pool is more complex, especially for the principle of the thread pool is not very clear, the thus provides static factory method in which Executors tools, generating some common thread pool, as follows:

newSingleThreadExecutor: create a thread pool of single-threaded. This is only a thread pool thread work, which is equivalent to a single-threaded serial execution of all tasks. If this thread only because of abnormal termination, then there will be a new thread to replace it. This thread pool to ensure that the order of execution of all tasks presented to the order of tasks.

newFixedThreadPool: create a thread pool of fixed size. Each time you submit a task to create a thread, until the thread pool thread to reach the maximum size. Once the size of the thread pool reaches the maximum will remain unchanged, because if a thread execution abnormal end, the thread pool would add a new thread.

newCachedThreadPool: Creating a cached thread pool. If the size of the thread pool threads exceeds the processing tasks required, it will recover partially free (60 seconds does not perform the task) threads, when the number of tasks, this thread pool and intelligently add a new thread to handle the task. This thread pool do not restrict the size of the thread pool, thread pool thread maximum size depends entirely on the size of the operating system (or JVM) that can be created.

newScheduledThreadPool: Create an unlimited size of the thread pool. This thread pool to support the timing and the need to perform tasks periodically.

newSingleThreadExecutor: create a thread pool of single-threaded. This thread pool to support the timing and the need to perform tasks periodically.

The relationship between the basic state of the thread and state?
Description: Running which indicates the operating state, Runnable represents a ready state (everything is ready, only a strong CPU), Blocked represent blocking state, blocking state there are a variety of situations, it may be because the call wait () method into the waiting pool, it may be the method of synchronization blocks or synchronization code into the lock pool the like, or a call sleep () method, or join () method, or the end of the other threads wait for dormancy, or because of a I / O interrupt.

Description of the similarities and differences between synchronized and java.util.concurrent.locks.Lock?

A: Lock is the new API after 5 introduced Java, and keyword synchronized compared to the same main point: Lock to complete all the functions synchronized achieved; the main differences: Lock more accurate than synchronized thread semantics and better performance, but not a mandatory requirement must acquire the lock. synchronized automatically release the lock, and requires the programmer must manually Lock release, and is preferably released (this is the best place to release the external resource) in a finally block.

How to implement Java serialization, what is the point?

A: is a kind of serialization mechanism for an object a process stream, that is, so-called content object stream object to be fluidized. After the fluidized objects can read and write operations, the object can also be transmitted after fluidizing between networks. Serialization is to solve the problems may arise when reading and writing a stream of objects (if not the sequence of data may be problematic scrambled).

  To implement the sequence, it is necessary to make a class implements Serializable interface, which is an identifier of an interface, such labels may be serialized objects are then used to construct an output stream and output stream through an object writeObject (Object) method write objects can be achieved (i.e., to save its state); if necessary to deserialize the input stream can be an input stream to create an object, then the object is read from the stream by readObject methods. In addition to the sequence of persistent objects can be achieved, but also can be used to clone the depth (refer to the first 29 questions).

Java There are several types of flow?

A: byte stream and character stream. Byte stream inherited from InputStream, OutputStream, a stream of characters inherited from Reader, Writer. In java.io package There are many other streams, mainly to improve performance and ease of use. About Java I / O to note two things: First, two kinds of symmetry (the symmetry of the input and output, and a character byte); the second is two design modes (mode adapter mode and decor). Further flow in Java is that it is different from the C # a dimension in one direction only.

Due to space limitations, only the author of the collection of java face questions and answers mentioned above, need more surface level answer questions students can private letter I "interview questions" get, like the author of this article can give a point endorsed, look, Java will share relevant articles every day! There are benefits presented from time to time, including the consolidation of learning materials, interview questions, such as source code ~ ~

Guess you like

Origin blog.51cto.com/14440597/2421223