java Basics

Collections:

  collection: parent interface, a set of collections length is not fixed, the fixed length of the array

    add () - add an element

    addAll () - Add a collection of elements

    clear () - Empty treatment

    contains () - is included

    equals () - Method obj override determines whether the object is equal to

    hashcode () - Method obj rewriting, the hash code determines whether the same object

    isEmpty () - Empty sentence

    iterator () - returns an iterator Iterator, hasNext () and next () iterates

    remove () - remove an element

    size () - returns the size of the collection element

    toArray () - into an array

  list:

    add (index, xxx) - additive element specified position

    addAll (index, xxx) - Add the specified position collection element

    get (index) - Returns the position of the element

    indexOf (obj) - an element index in the set

    lastIndexOf (obj) - an element set in the last occurrence of the subscript

    remove (index) - Removes the specified location element

    set (index, obj) - replacement of the designated location element

    subList (from, to) - Returns the current index range of elements

    sort (Comparator) - Sort Sort Parameters

    toArray () - into an array

arraylist:

  An array implementation. Space-saving, but the array has a limited capacity. 50% increase in capacity would limit is exceeded, with System.arraycopy copy () to the new array, thus better able to give an estimate of the size of the array. Create an array of size 10 when the insert elements default for the first time. Access elements in the array, -get very high standard (i) / set (i, e) performance, which is the basic advantage of the array.

  Added elements -add (e) directly in the end of an array of high performance, but if the pressed header inserting, deleting elements -add (i, e), remove (i), remove (e), the use System.arraycopy ( ) to move the affected part of the elements, the performance deteriorates, which is the basic disadvantage. When the data increase the time, if the size of the ArrayList demand has been satisfied, then the array will become 1.5 times the original length, after the operation is the old array copying new array inside.

LinkedList is a simple data structure, and ArrayList is different is that he is on the list to achieve.

 

hashmap:

  There are two very important parameters, the capacity (Capacity) and the load factor (Load factor) in the HashMap

  Capacity is the size of the bucket, Load factor is the ratio of the maximum degree of fill bucket. If the iterative performance requirements of very high, not to capacityset too high, it should not be load factorset too small. (0.75) when the number of entries is larger than the bucket capacity*load factorwhen the bucket need to adjust the size of two times the current  

  General idea put function:

  1. The key to hashCode () do the hash, then the index is calculated;
  2. If you do not crash directly into the bucket inside;
  3. If the collision, the presence of the buckets in the form of a linked list;
  4. If collisions result in long chain (greater than or equal TREEIFY_THRESHOLD), the list is converted into a red-black tree put;
  5. If the node already exists on replacing old value (ensure the uniqueness of the key)
  6. If the bucket is full (over load factor*current capacity), it must resize.

  get function

  

  1. bucket in the first node, a direct hit;
  2. If there is a conflict, then by key.equals (k) to find the corresponding entry

    If the tree, the tree is searched by key.equals (k), O (logn);

    If the linked list, the list is searched by key.equals (k), O (n).

HashMap does not guarantee data order, LinkedHashMap ensure that the data can be inserted to keep order, but if we want to keep the key can Map of the order, we will need to use a TreeMap.

The advantage of using red-black tree that enables a tree with good balance, so that the operation speed can reach a level log (n) of the.

 

LinkedHashMap achieve Hash table and linked list, and rely on a doubly linked list to ensure that the iterative sequence is the order of insertion.

 

Generics:

Wildcard: <?> <? Extends shape> <? Super shape> upper limit wildcard subclasses shape or limit itself or wildcard shape of the parent class itself

 

Proxy mode:

An object to provide a proxy object, the proxy object by controlling the access to the original object, that is, customers do not directly manipulate the original object, but by manipulating the original object proxy object indirectly.

Static proxy: proxy class is at compile time to achieve good. That after the completion of the Java compiler proxy class is an actual class file.

Audience (RealSubject) and a proxy object (Proxy) implements the interface theme (Subject). In the proxy object (Proxy), passing through the constructor of the target object (RealSubject), then rewrite request topic Interface (Subject) of () method is called the target object (RealSubject) in the method of the request () method, and You can add front and back () method of some additional work while the target object (RealSubject) of the request.

class Proxy implements InterfaceClass {

  private InterfaceClass obj

  public Proxy(InterfaceClass obj) {

    this.obj = obj

  }

  public void xxxMethod() {

    prehandle ()

    obj.xxxMethod()

    lasthandle()

  }

}
Dynamic proxy: proxy class is generated at runtime. That is, after compiling the Java class and not the actual file, but generated dynamically at run-time class bytecode, and loaded into the JVM.

Dynamic proxy is a proxy class dynamically generated at runtime. That is, the proxy class bytecode and loads the current generated at runtime ClassLoader agent.

class Proxy implements InvocationHandle {

  private InterfaceClass obj

  public Proxy(InterfaceClass obj) {

    this.obj = obj

  }

  public Object invoke(Object proxy, Method method, Object[] args) {

    prehandle ()

    Object result = method.invoke(obj,args)

    lasthandle()

    return result

  }

}

 

Abstract classes and interfaces classes

  1. Abstract classes and interfaces can not be instantiated directly, if instantiated, abstract class variables must point to implement all the abstract methods subclass object, the interface variable must point class object implement all interface methods.
  2. Abstract class to be inherited by subclasses, the interface class to be realized.
  3. Variables defined in the interface can only be public static constants, the abstract class variables are common variables.
  4. Abstract class can no abstract methods.
  5. Class multi-interface can be achieved (by other interfaces multiple inheritance), abstract class can only inherit sheets.
  6. No interface  this pointer, no constructor has not instance field (instance variables) or instance method.
  7. Abstract classes can not be used in Java lambda expression 8.

 

Shallow vs. deep copy

Shallow copy is a copy of the object, it creates a new object that has the original object of an exact copy of the property value. If the attribute is a value of the basic type of basic types, copied; if the attribute is a memory address (a reference type), the memory address is copied, so if one of the objects of this address is changed, it will affect the other object.

Deep copy will copy all attributes, and attribute points to the copy memory dynamically allocated. Objects and object when it refers to the copy of deep i.e. with copy. Deep copy shallow copy slower compared to larger and expenses.

 

Serialization: compliance Serializabel

1) Once the variables are modified transient, variable object persistence will no longer be part of the variable content after serialization can not gain access.

2) transient keyword can only modify variables, methods and classes can not be modified. Note that local variables can not be modified transient keyword. If the variable is a user-defined class variables, the class needs to implement Serializable interface.

3) modified transient key variables can no longer be serialized, regardless of whether a static variable is transient modification, not be serialized.

 

Exception trap

try the return statement execution has been carried out again finally statement, but there is no direct return, but finally statement execution and other finished and then returns the result.

finally block the return statement coverage try block or catch block return to return.

The catch statement executes the return, the return value is determined and then to the finally block, then return catch finished execution.

If not finally block the return statement, modify variables finally, if the amount of change itself, does not affect the return value, if an element and an attribute modifying the internal variable, it will affect the return value.

 

Multithreading:

Adopted to achieve Runnable, Callable interface when Transcend way multithreaded, the advantage is:

Thread class implements Runnable interface or just Callable interface, you can also inherit from other classes.

In this way, multiple threads may share the same target object, is the same for a plurality of threads to deal with a case where the same resources, which can be separated to form a clear model of the CPU, code and data, to better reflect the object-oriented thinking.

Disadvantages are:

Programming is slightly more complicated, if you want to access the current thread, you must use Thread.currentThread () method.

When using inheritance Thread class way to create multi-threaded advantages are:

Write simple, if you need access to the current thread, you do not need to use Thread.currentThread () method, the direct use this to get the current thread.

Disadvantages are:

Thread class Thread class has been inherited, so can not inherit other parent.

 

lock:

synchronized: object lock, the lock can also be used as a class

ReentrantLock: display acquire and release locks

Lock: display acquire and release locks

When a thread obtained when an object, the object lock is again requesting the lock of the object can be obtained again.

The concept is specific: they can get their own internal lock again.

Java inside the built-in lock (synchronized) and Lock (ReentrantLock) are reentrant.

ReentrantLock is locked in a fair, equitable by passing true that lock in the constructor, passing false, is unfair lock. Fair locks can guarantee a chronological thread of execution, to avoid starvation.

synchronized when an exception occurs, it will automatically release the thread owns the lock, it will not lead to a deadlock phenomenon; and Lock when an exception occurs, if there is no initiative by unLock () to release the lock, then it may cause a deadlock and, therefore, need to release the lock when used in a finally block lock;

By Lock can know by tryLock / isLocked have not been successful to acquire the lock, and synchronized it can not be done.

ReadWriteLock is read-write locks, it is an interface, ReentrantReadWriteLock implements this interface.

Can () to obtain a read lock by readLock, () to obtain a write lock by writeLock.

Wait and notify methods have methods associated with the class Object. Because the wait and notify methods defined in the class Object, so all will be inherited by the class. These methods are final, i.e. they are not to be rewritten can not be overwritten by the subclass to change their behavior.

The current thread must have a current monitor objects, that lock, is a lock to call wait () method, otherwise it will throw an exception java.lang.IllegalMonitorStateException.

Thread calls wait () method to release ownership of the lock it, and then wait for another thread to notify it (by means of notice is notify () or notifyAll () method), so that it can regain ownership of the lock, and resumes execution .

To ensure that the call wait () method when the lock has, namely, call wait () method must be placed synchronized method or synchronized block.

The awakened thread can not be executed, it is necessary to wait until the current thread to give up the object's lock, the current thread is executed after completion of the release lock method.

wait () / singal () is similar to the conditon wait () / singal ()

 

Generally, a processor in order to improve process efficiency, might enter the code optimization, it does not ensure the implementation of the program in individual statements in the order consistent with the order of the code, but it will ensure the implementation of the program and the final results of the code execution order the result is the same. Since the reordering is performed when the processor considers data dependencies between instructions, if the statement is a statement results 1 2 must be used, then a statement will ensure that the processor executes the statement 2 before.

 

When shared variables in multi-threaded, if you want variables to take effect immediately, use the volatile modifier

Guess you like

Origin www.cnblogs.com/diyigechengxu/p/11340935.html