The java language

1. collections

The main grasp how.

The principle points summarize ArrayList

List ArrayList variable is an array of non-synchronous interfaces to achieve, and permits all elements, including null, including.
Underlying implemented using an array
of the set is a variable length array, an array expansion, will cause the old elements in the array to re-copy the new array, each array is about 1.5 times the capacity increase its capacity, this operation costly.
Uses a Fail-Fast mechanism, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary deterministic behavior at an undetermined time in the future
the remove method will subscript to the end of the array the element is moved forward by one unit, and the last bit of value left blank, convenient GC

The principle points summarize LinkedList
LinkedList is a doubly linked list List of asynchronous interfaces to achieve, and permits all elements, including null, including.
Underlying data structure is based on a doubly linked list, which we referred to as node data structure
example of a doubly linked list corresponding to the node Node class, the Node member variables included: prev, next, item. Wherein, prev one node in the node, next is the next node of the node, item is contained in the value of the node.
It lookup lookup is two and a half, the first index is determined in which half of the list, then go to find the corresponding region, so long as up to half traverse the list to find a node

The principle outlined points HashMap
Map interface HashMap non hash table is based on the synchronous implementation, null null value is permitted and the key, but does not guarantee the order of mapping.
Underlying implemented using an array, each array is a one-way linked list, i.e. an array and combination chain; when the chain length is greater than a predetermined threshold value, the list is converted into a red-black tree, thus reducing the query time list.
At the bottom the HashMap key-value be processed as a whole, this is an overall Node objects. HashMap bottom using a Node [] array to store all of the key-value pairs, when required to store a Node objects, will decide its storage position in the array according to the hash algorithm key in its decision in the array according to the equals method position on the list of storage locations; Node when a need to remove, will also find its storage position in the array based on the hash algorithm key, and then removed from the list of the Node on the position according to the equals method.
HashMap array for expansion need to recalculate the position of each element in the array after expansion, a waste of performance
using the Fail-Fast mechanism, through a number of modifications modCount value record, modifications to the HashMap content will increase this value. Iterator initialization process will assign the value iterator expectedModCount, in an iterative process to determine whether expectedModCount modCount with equal, if not equal, says there are already other thread modifies Map, immediately throw an exception

The principle point summarized Hashtable
Hashtable Map interface is synchronous implementation based on the hash table, and null values are not allowed null keys
underlying implemented using an array, each array is a single chain, i.e., a combination of arrays and linked lists
Hashtable at the bottom the key-value process as a whole, this is a whole Entry object. Hashtable bottom using a Entry [] array to store all of the key-value pairs, when required to store a Entry object, will decide its storage position in the array according to the hash algorithm key in its decision in the array according to the equals method position on the list of storage locations; Entry when a need to remove, will also find its storage position in the array based on the hash algorithm key, then remove the Entry from the list according to position on the equals method.
Hash is synchronized for the entire table, that is, each thread to exclusively lock the entire table

The principle outlined ConcurrentHashMap points
ConcurrentHashMap concurrently allowing multiple modifications, which lock key is used separation techniques.
It uses multiple locks to control changes to a different segment hash table performed, each segment is actually a small hashtable, they have their own locks. As long as a plurality of concurrent occur on different segments, they can be complicated.
At the bottom ConcurrentHashMap the key-value be processed as a whole, this is a whole Entry object. Hashtable bottom using a Entry [] array to store all of the key-value pairs, when required to store a Entry object, will decide its storage position in the array according to the hash algorithm key in its decision in the array according to the equals method position on the list of storage locations; Entry when a need to remove, will also find its storage position in the array based on the hash algorithm key, then remove the Entry from the list according to position on the equals method.
The difference is that the HashMap, using a plurality of ConcurrentHashMap Hash sub-tables, i.e. segment (Segment)
of ConcurrentHashMap completely concurrently allowing multiple read operations, a read operation does not require locking. If using conventional techniques, such as the HashMap implementation, if allowed to add or delete elements in the middle of the hash chain, the read operation does not lock the resulting inconsistent data. ConcurrentHashMap implementation technology is to ensure HashEntry almost immutable.

The principle points summarize HashSet
HashSet (actually a HashMap instance) supported by a hash table, does not guarantee the iteration order of the set, and allows the use of null elements.
Based HashMap achieved, the API HashMap is also the conduct of the package, refer HashMap

The principle elements are summarized LinkedHashMap
LinkedHashMap inherits the HashMap, bottom and two-way linked list using hash tables to store all of the elements, and it is asynchronous, and the null values allow null keys.
The basic operation is similar to the parent class HashMap, HashMap related methods by rewriting, re-defined the save array elements Entry, to realize their link list of features. In addition to the Entry to save the current references to objects, but also saved on an element before and after reference to the next element, which constitutes a two-way linked list.

The principle LinkedHashSet summarize key points
for LinkedHashSet, for its inheritance and HashSet, and implemented based on LinkedHashMap. Use LinkedHashMap LinkedHashSet bottom to hold all the elements, which inherits the HashSet, and the same operation with all its HashSet method.

2. Dynamic Agent and reflection
is a feature of java language, you need to master the use of dynamic proxies scene with reflection.
ORM framework will be extensive use of proxy class uses reflection to call when PRC implementation class method calls.

java dynamic proxy reflection is achieved.

What is reflection?
java reflection mechanism, is that at run time, for any class, are able to know all of its properties and methods; for any one object, are able to call any of its methods and properties; this dynamic access to information and dynamic method invocation the feature is called java reflection mechanism.

java class java.lang.Class achieved by reflection.

Class Class getDeclaredMethod can return a method method name:

// Returns a Method object that reflects this Class object represented by the specified class or interface method declarations.
GetDeclaredMethod Method, (<?> String name, Class ... parameterTypes)
1
2
Method, invoke method can execute this method:

// the specified object with the specified parameters of the method call thereby Method object underlying representation.
Object invoke (Object obj, Object ... args)


3. Data types
are also common interview questions such as how much space occupied by each data type, data type conversion and automatically cast, the underlying data type and data type Wrapper automatic boxing and unboxing and so on.

First, the basic data types:

byte: the smallest Java data types, representing the memory 8 ( 'bit), i.e., one byte, in the range -128 to 127, the default value 0
Short: short integers, representing the memory 16, i.e., 2 bytes, the range from -32768 to 32717, a default value 0
int: integer, for storing integer, including 32, i.e. four bytes, in the range -2147483648 to 2147483647, the default value representing 0
long: long integer, representing the memory 64, i.e., 8 bytes -2 ^ 63 to 2 ^ 63-1, the default value 0L
a float: float, in the accounting memory 32, i.e., 4 bytes , for storing a decimal point number (float and double difference is only 6 ~ type valid decimal 7), the default value 0
double: double precision floating point, with a decimal point for digital storage, accounting for 64 in memory bits, i.e., 8 bytes, the default value
char: character, for storing a single character, representing 16, i.e., 2 bytes, in the range 0 to 65535. The default value is empty
boolean: a type, accounting for a byte, for judging true or false (only two values, i.e. to true, false), the default value of false

Java data types stored in memory:

1) basic principles of data storage types: simple data types are not all the concept of "references" exists, the value of the data itself on the memory stack for basic data types are stored directly in the memory is stored in the stack space inside, while Java is a language which eight kinds of data types such storage model;

Storage principle 2) reference types: Reference types inherit from the Object class (also a reference type) are in accordance with the Java memory model inside the storage object for data storage, the use of Java memory heap and stack memory to perform this type of data storage , Simply put, the "reference" is stored in the memory and orderly stack, and the value of the object itself is stored in memory on the heap;

Difference: the difference between the basic data and reference types of basic data types are mainly allocated on the stack, and reference types are allocated in the heap (stack requires the java, reactor concept),

The memory model is essentially primitive types and reference types are not the same.

Example 1: We analyze the difference between "==" and equals () is.

First, I set two String objects

Stringa="abc";

Stringb="abc";

then

if(a==b){

System.out.println("a==b");

}else{

System.out.println("a!=b");}

Program outputs a! = B

Reasons: a and b are not the same address, a == b is the address of two comparison variables

Example 2: define two basic types of

int a=4;

int b=4;

if(a==b){System.out.println("a==b");}

else

{System.out.println("a!=b");}

Output: a == b

The reason: == compares the contents of two variables

Guess: whether the basic data type or reference type, they will allocate a block of memory on the stack, the basic types, this region contains the basic types of content; and the object types, this area contains pointer is a pointer to the real content, a real content being manually allocated on the heap.


4. The object reference
(self-search)

Java foundation often test centers -Map
able to examine the data structures, java achieve mastery of foundation and roadmap for concurrency problems.
A, HashMap
achieved by adding an array of linked lists.
Array element is a list, by calculating into a class hashcode, confirmed into position, using the hash list to resolve the conflict. node list is stored in key-value pairs.

The role of the fill factor
rehash mechanisms Map expansion of
capacity is a power of two.
Is to facilitate the operation and bit computing remainder, modulo faster than the
cause of multi-threaded risk
of thread put, the case will more than fill factor in to avoid tail rehash.HashMap traversing the linked list insertion head using interpolation, may produce death cycle multithreaded scenario.

Two, of ConcurrentHashMap
segment lock Thought
1.7 segmented locking segment used to reduce the degree of locking concurrency.
CAS spin lock
time spinlock 1.8 using CAS (locks for an optimistic mode) to improve performance, but at a higher degree of concurrency , performance in general.
black tree
1.8 when introduced into the red-black tree list of hash conflicts resolved to find the problem. 8 and the chain length is more than the total capacity of greater than 64 is enabled when the list length is less than 6 after the re-expansion into a general list (8, 6,64 to default parameters)

Java Version Features
1.8
* the Lambda expressions
* StreamAPI
* Method Reference
* Interface default method
* Metaspace replace PremGen

1.9-1.10
* modular system
* default Collector G1
* Private method Interface
* local variables determined
* compiler Graal

1.11
* ZGC
* string API Enhancements
* Built-in HTTP Client


Interview inspection point
1. The implementation and use
* HashMap implementation manner of JDK1.8

Expansion is an element of the old array to the new array

1, HashMap underlayer is a doubly linked list arrays + + red-black tree implementation
2, when the element is inserted, is first obtained by a method of calculating the hash value of the hash key, and then the calculated insert position
3, if the location is empty , directly into the (packaged in the Node)
. 4, if the location has a value, it is in turn traversed. Rules of comparison, the same hash value, equal to the value of the key elements considered the same, then replace the old value with the new value and return the old value.
5, if the position of the element is red-black tree structure, the same token, find, find the replacement, did not find the insert.

Plan Key:
JDK1.8 and JDK1.7 in HashMap There are a lot of places are not the same
, 1.8 introduced a red-black tree, but not the 1.7
elements 2,1.8 is inserted at the end of the list, while 1.7 is the new element inserted in the head of the list
3, expansion, when 1.8 does not appear in an infinite loop, while the 1.7 infinite loop prone, but the list will not be inverted


2. practical application fallible point
* == What is the difference equals

"==" and equals method is what is the difference?
(A single thing to say clearly, clearly and then say another, so that they came out of the difference between natural, mixed together that it is difficult to say clearly)

== operator designed to compare two values are equal, i.e. for comparing the variables corresponding to the values stored in the memory are the same, to compare two basic types of data or two reference variables are equal, == operator can only be used.
If the variable points to a data object type, then this time involves two memory occupied by the object itself a memory (heap memory), a memory occupancy variables, e.g. Objet obj = newObject (); obj is a memory variable , new Object () is a second memory, at this time, the value stored in memory corresponding to the variable obj is the object occupies the first address of that memory. For variable type pointing object, if you want to compare two variables refer to the same object, i.e., the value depends on two variables corresponding to the memory are equal, this time need to be compared with == operator.

equals method is used to compare the contents of two separate objects are the same, like is the same ratio to compare the appearance of two people, it compares two objects are independent. For example, the following code:
String = A new new String ( "foo");
String B = new new String ( "foo");

Two statements create two new objects, then a / b of these two variables point to one object, which is two different objects, they are different from the first address, i.e., values of a and b stored is not the same, therefore, the expression a == b will return false, and the content of these two objects are the same, therefore, the expression a.equals (b) returns true.
In the actual development, we often want to compare the string to be passed such as whether the content, for example, String input = ...; input.equals ( "quit"), a lot of people a little attention on the use == to compare, this is wrong, just to find a few items of practical instructional videos from the internet to see, which have a large number of such errors. Remember, basically string comparison using the equals method.
If a class does not define its own equals method, then it equals method of Object class inheritance, equals method of Object class codes are as follows:
Boolean equals (Object O) {
return the this == O;
}

This means that if a class does not own definition of the equals method, which by default equals method (inherited from the Object class) is to use the == operator, also comparing two variables point to whether the object is the same object, and this time the use of equals use == you will get the same results, if the comparison of two separate objects are always returns false. If you want to write the kind of content can compare two instances of objects created from that class is the same, then you must override the equals method to you to decide what to write code that can be considered in the content of the two objects are the same.
-------------------------------------------------- ---------------
simply put, if == to compare two people what is really the same person, equals generally used to compare two people are equal in logic (such as providing two adult after even if the same two people the same height, etc.), thinking about how to define the definition of how, if you do not override the equals method, the default is still relatively the same whether the two individuals (nonsense, two people are still in the embryonic state, are not specific features, how which may be logically).


* Object strong references improper use can cause memory leaks, examine different understanding of the role of reference and
resolve memory leaks just said, under the main use is to explicitly declare the type of reference, a brief explanation of relevant knowledge:

 1, type of reference: strong, soft and weak. Ordinary java references, but also our most general java object reference, is strong references, it directly affects garbage collection (there is a strong reference to the object corresponding point, GC will not recover the object, even if not enough memory); soft references the main difference and strong references are: it will affect the GC recycling of objects, however, when the virtual machine's memory is not enough, soft reference points to an object (of course, can not have a strong reference to an object at the same time) are mandatory recycling; weak references on a lower level, it can not affect the work of the GC garbage collection object, can only refer to and access objects. Specific reference may be illustrated by the following three kinds of code example:

// use soft references cited examples and weak
public void referenceExam () {
Object object = new new Object (); // this is a general object references cited strong
// create a soft soft references cited by the SoftReference
the SoftReference <Object> = softObjReference the SoftReference new new <Object> (Object);
// get acquired by the real object reference method
softObjReference.get ();
// weak references to associate an object by WeakReference
WeakReference <Object> weakObjReference new new WeakReference = <Object> (Object);
weakObjReference.get (); // this method returns a reference to the real object, when there is no strong or weak reference point to reference it returns null

}
  
2, memory leaks and to prevent the strength of the type of garbage collection related references, we can summarize the following features:
  A, when we larger object cache in the cache buffer, for example, pictures, etc. to improve the reading speed when (for large memory object problem) can be related to the object as a soft reference object, thus ensuring that work can be recovered GC when memory is not enough.
  B, when we are not entirely due to the reference current recovery period GC other modules affect the original set of objects of the object, we can reference weak (only access to the data corresponding to access and use without causing recovery of the object to GC influence)
  C, of course, java there is something called phantom reference is a reference type variable, which is in fact the reality could not be used much, mainly used to track objects GC process, so do not talk about in detail here.
Finally, as to when to set the target for the weak reference (or soft references), personally think it should be judged objects used depending on the business, if the global object is too large, it may cause leaks in the program, or that we do not want when the object is not clear when they can be recovered (to the customer by providing an object factory interface), reference may be soft or weak reference for object access.

 

Anti embodiment described hazards actual scene misuse.
E.g., using a large number of reflection affect performance.


Associated with knowledge of the latest technology trends.
For example, talked about ConcurrentHashMap, we can introduce improved details 1.8.

 

Zhenti summary of
a role in the Object equals and hashcode are what is?
1 These two methods are from java.lang.Object class in Object hashCode () returns the address of the value of the object, equals () method is address comparison performed two objects; if equals () method returns the same value, indicating the address value of the two objects are the same, hashCode () return value are the same.

When Rule 2 is added to the collection element (e.g. HashSet, TreeSet, etc.) is followed by:
a value of A hashCode determination target is the same, if not identical, that these two elements are not the same, if the same, into B.
Judgment value B equals two operation objects are the same, if not identical, that the two objects are not the same,
if the same two objects that are identical.

3 when the added elements to an object class package, since the package has been rewritten based hashCode () and equals () method,
so the method used here is two rewrite their own wrapper class. So long as the deposit is considered to be the same as the contents of the same object.

4 custom object class is added to the collection, if the custom class does not override equals () and hashCode () method is called Object of these two methods, i.e. hashCode () method produces a value hashCode (forever not the same address), then use equals () methods were compared (address); it may produce added prior to the collection of objects, because of the two values ​​produced hashcode is different, equals () method that this is not the same elements added twice, resulting in a collection of objects have duplicate elements appear. The solution is: rewrite these two methods custom class.

5 hashCode () method is often used together and a set of hashes (HashSet, HashMap, HashTable),
If not duplicate set of elements, if equals () are compared, it will produce efficiency.
So use hashCode () method, while adding elements to ensure the uniqueness of the element.
6, if a class overrides the equals () method, it must also override hashCode () method, because: Although equals () methods can ensure proper override logic determines whether the same two objects, but hashCode () method physical address mapping is not the same, the same will still logically into a set of two elements, but the content of the second object will be Null.

Two, final, finally, finalize distinction and usage scenarios
(1) final: as a modifier modifying variables, methods and classes, modified final variables assigned only once; the final process can not be modified in subclasses rewriting (override); modified final class can not be inherited.
 (2) finally defined in exception handling code is always executed, regardless of whether the try block code throws an exception, if the matching is successful catch, the finally block code is always executed, unless the JVM is closed (System.exit (1 )), commonly used as an external release resources (not recovered garbage collector resources).
 (3) finalize () method is a method defined in the class Object, when the garbage collector unwanted objects from the memory, finalize the object () method is called. Since the method is protected method, a subclass can override the (override) the method to organize resources or perform other cleanup work. (Likely target will be resurrected)


Third, simple statements about Java's exception mechanism
Java exception mechanism depends on the try, catch, finally, throw, throws five keywords.

1.try: it may throw an exception is placed inside code

2.catch: a behind the corresponding code block and exception types, indicating that the catch block for processing this type of block, can have multiple catch blocks.

3.finally: mainly used for material recycling opened in a try block (such as database connections, network connections and disk file), exception mechanism always guarantee that the finally block is always executed. Only finally block, after the execution is complete, it will come back the try or catch block return or throw statement, if finally used in the statement termination method of return or throw, etc., then it will not jump back to perform, direct stop.

4.throw: for a practical throw exception, may be used alone used as a statement, a specific exception object is thrown.

5.throws: used in the method signature for this method may throw exception statement.

 

Java's exception divided into two types, checked abnormality (abnormal compile time) and Runtime exception (a runtime exception)

1. java think checked exceptions are an exception can then compile phase is processed, so it forces the program handles all checked exceptions, while having to deal with abnormal Runtime, java program must explicitly deal with checked exceptions, if the program does not deal with, then the compiler error occurs, it can not compile.

2. checked java anomaly reflects the design philosophy: there is no perfect treatment code will not be executed, reflects the rigor of java,


Fourth, the use of the online version of jdk, why use this version (what are the characteristics)?

 

Guess you like

Origin www.cnblogs.com/muzinan110/p/11105699.html