Java Interview Topics Collection _java

Source: Internet
Author: User
Tags float double hash modifier reflection sql injection thread class volatile

The 1.equals method is used to compare the contents of an object to equality (after overwriting)

The 2.hashcode method is only used in the collection

3. When the Equals method is overridden, comparing the equality of the objects will be compared through the overridden Equals method (to determine if the object's contents are equal).

4. When you put an object into a collection, you first determine whether the Hashcode value of the object you want to put into the set is equal to the hashcode value of any element in the collection, and if it is not equal, put the object directly into the collection. If the hashcode value is equal and then the Equals method is used to determine whether the object is equal to any object in the collection, if the equals judge is not equal, the element is put into the collection directly, otherwise it is not placed.

5. No Override Equals method uses object memory address equality to determine whether objects are equal.

The object's memory address is not equal because it is two new objects, so Stu1.equals (STU2) is false.

6. Both threads A and b obtain the lock of object o, assuming that a acquires the object o Lock, B will wait for a to release the lock on O, if the use of synchronized, if a does not release, B will keep waiting, can not be interrupted if a reentrantlock is not released, You can make B wait long enough to interrupt the wait and do something else.

Reentrantlock gets locked with three ways:

A) lock (), if the lock is returned immediately, if another thread holds the lock, the current thread remains dormant until the lock is acquired

b trylock (), returns True if the lock is acquired immediately, and returns False if the other line one thread hold the lock;

c) Trylock (long timeout,timeunit unit), if a lock is acquired immediately returns true if the other line one thread hold the lock, waits for the parameter given time,
Returns true if a lock is acquired in the process of waiting, false if waiting for a timeout;

D lockinterruptibly: If the lock is returned immediately if acquired, if the lock is not acquired, the current thread is dormant until or locked,
Or when the line is interrupted by another thread

Synchronized is implemented at the JVM level, not only with some monitoring tools to monitor synchronized locks, but also when code execution occurs.
The JVM will automatically release the lock, but using lock is not possible, lock is implemented by code, to ensure that the lock will be released, you must put unlock () in the finally{}

In the case of resource competition is not very intense, synchronized performance is better than Reetrantlock, but in the case of intense resource competition, synchronized performance will fall dozens of times times, but Reetrantlock performance can maintain the normal;

In JDK, the Java reflection mechanism is implemented primarily by the following classes, all in the Java.lang.reflect package:

Class Classes: Represents a class.

Field class: Represents a member variable of a class (a member variable is also called a property of a class).

Method classes: Methods that represent classes.

Constructor class: Represents the construction method of a class.

Array class: Provides a static method for dynamically creating an array and accessing the elements of an array.

Here are a few examples to see how the Reflection API actually applies:

Get member variables, member methods, interfaces, superclass, construction methods, etc. through class class

The GetClass () method is defined in the Java.lang.Object class, so for any Java object, you can get the type of the object in this way. The class class is the core class in the Reflection API, and it has the following methods

GetName (): Gets the full name of the class.

GetFields (): Gets the properties of the class's public type.

Getdeclaredfields (): Gets all the properties of the class.

GetMethods (): Method that gets the public type of the class.

Getdeclaredmethods (): Gets all the methods of the class.

GetMethod (String name, class[] parametertypes): Gets the specific method of the class, the name parameter specifies the method, and the Parametertypes parameter specifies the parameter type of the method.

GetConstructors (): Gets the constructor for the public type of the class.

GetConstructor (class[] parametertypes): Gets a specific constructor for the class, and the Parametertypes parameter specifies the parameter type of the constructed method.

Newinstance (): Creates an object of this class through a class-without-parameter construction method.

To write a Java reflection program:

1 must first get the class object

For example:

Class C1 = Test.class;
Class C2 = class.forname ("Com.reflection.Test");
Class C3 = New Test (). GetClass ();

2) Then call the method in the class object separately to get the structure of the property/method/construct method of the class

Note: If you want to be able to get the normal method/attribute/construct method in the class, you should focus on the following reflection class

Field

Constructor

Method

<servlet-mapping> 
<servlet-name></servlet-name>
<url-pattern></url-pattern > 
</servlet-mapping> for 
(String elementa:str) { 
System.out.print (Elementa + ""); 
} 
list<string> list = new arraylist<string> (); 
for (int i=0; i<str.length; i++) { 
if (!list.contains (str[i))) { 
list.add (str[i]); 
}
set<string> set = new Hashset<string> (); 
for (int i=0; i<str.length; i++) { 
set.add (str[i]); 

Spring has six kinds of transaction five isolation levels

First class: integer byte short int long

Type two: float double

Category III: Boolean (it has only two values to be true false)

Class Fourth: Character Char

Methods in the final modifier class

Function: Can be inherited, but cannot be overridden after inheritance.

Final Cosmetic class

Function: A class cannot be inherited.

Final modifier basic type when the value is the same, the reference type represents the same address, which is new when the address can not be assigned a value

Final Cosmetic properties you know that.

Preparestatement is precompiled, first the SQL submitted to the database for preprocessing, and then put it into the cache, the next found that there is the same without compiling, high efficiency, syntax prompts easy to check, parameters are dynamic, prevent SQL injection because of the grammar check

 
 

Statement is not precompiled and requires a manual check for syntax errors, which are hard coded

HashMap allows NULL to be used as a entry key or value, and Hashtable does not allow

Put method

HashMap the null value key for special processing, always put to the table[0] position putting process is to calculate the hash and then through the hash and table.length to calculate the index value, and then put the key to the Table[index position, When Table[index] already has other elements, it will form a linked list in the Table[index] position, placing the newly added elements in Table[index], and the original elements are linked through the entry next, thus solving the hash conflict problem in a linked list, When the number of elements reaches a critical value (Capactiy*factor), the expansion is done, and the length of the table array becomes table.length*2

Get method

Similarly, when the key is NULL, special processing is done, and the element with the key null is found on the list of table[0]

The process of get is to compute the hash first and then through the hash and table.length to calculate the index value, and then traverse the list on Table[index] until the key is found, then return HashMap and hashtable the underlying implementation is array + List structure to add, delete, get elements are calculated hash first, according to hash and Table.length Calculation index is table array of subscript, and then do the appropriate operation

Most of the indexes are based on B-Tree

Servlet Thread-safety issues are primarily caused by instance variables, so you should avoid using instance variables in the servlet.
If application design cannot avoid using instance variables, use synchronization to protect instance variables to use, but to ensure the best performance of your system, you should synchronize the least available code path.

Write a single case pattern

public static long recursive (int n) {
if (n <= 0) return
0;
if (n = = 1) return
1;
return recursive (n-1) + recursive (n-2);
}
public static long loop (int n) {
if (n <= 0) return
0;
if (n = = 1) return
1;
Long fib1 = 0;
Long fib2 = 1;
Long sum = 0;
for (int i = 2; I <= n; i++) {
sum = fib1 + fib2;
FIB1 = FIB2;
FIB2 = sum;
}
return sum;
}

Hashtable is a thread-safe class that uses synchronized to lock the entire hash table to achieve thread safety, that is, each time the entire table is locked so that the thread is exclusive. Concurrenthashmap allows multiple modification operations to be performed concurrently, and the key is the use of lock separation techniques. It uses multiple locks to control modifications to different parts of the hash table.

Concurrenthashmap internal use of segments (Segment) to represent these different parts, each segment is actually a small hashtable, they have their own locks. As long as multiple modification operations occur on different segments, they can be performed concurrently.

Some methods need to span segments, such as size () and Containsvalue (), and they may need to lock the entire table rather than just a segment, which requires locking all segments sequentially, and then releasing all the locks in order, after the operation has finished. Here "in order" is important, otherwise there is a high likelihood of deadlocks, within the Concurrenthashmap, the segment array is final, and its member variables are actually final, but simply declaring the array as final does not guarantee that the array member is final, This requires the assurance of implementation.

This ensures that deadlocks do not occur because the order in which locks are obtained is fixed

①threadlocal②synchronized () ③wait () and notify () ④volatile

ThreadLocal

ThreadLocal guarantee that different threads have different instances, the same thread must have the same instance, that is, each thread that uses the variable provides a copy of the value of the variable, and each thread can independently alter its own copy, instead of conflicting with the copy of the other thread.

Advantages: Provides thread-safe shared objects

Different from other synchronization mechanisms: Synchronization mechanism is to synchronize multiple threads of concurrent access to the same resource, is to communicate between multiple threads;
The ThreadLocal is a data-sharing that isolates multiple threads, essentially not sharing resources between multiple threads, which of course does not require multiple threads to synchronize.

Volatile

Volatile decorated member variables are forced to reread the value of the member variable from shared memory each time it is accessed by the thread. And

When a member variable is changed, the thread is forced to write the change value back to the shared memory.

Advantage: This way at any time, two different threads always see the same value for a member variable.

Reason: The Java language specification indicates that for optimal speed, a thread is allowed to save a private copy of a shared member variable.

It is only compared to the original value of the shared member variable when the thread enters or leaves the synchronized code block.

This way, when multiple threads interact with an object at the same time, it is important to notice that the thread gets the change in the shared member variable in a timely manner.

The volatile keyword is the hint VM: You cannot save its private copy for this member variable, but you should interact directly with the shared member variable.

Tip: Use volatile on member variables accessed by two or more threads.

You do not have to use when the variable you want to access is already in a synchronized code block, or it is a constant.

In order to improve efficiency, a thread copies a member variable (such as a) to a copy (such as B), and the access to a in the thread actually accesses B. The synchronization of A and B occurs only in certain actions, so there is an inconsistency between A and B. Volatile is used to avoid this situation.

Volatile tells the JVM that the variable it modifies does not retain a copy, and that it accesses the main memory directly (it is much better to read for a long time; communication between threads is not available in this article)

Volatile variables have synchronized visibility properties, but do not have atomic properties.

This means that the thread can automatically discover the most recent value of the volatile variable. The Volatile variable can be used to provide thread safety, but can only be applied to a very limited set of use cases: there is no constraint between multiple variables or between the current value of a variable and the modified value.

You can use volatile variables instead of locks in a limited number of situations. For the volatile variable to provide ideal thread safety, the following two conditions must be met:
Writes to a variable do not depend on the current value, and the variable is not included in the invariant with other variables.

Sleep () vs. wait ()

Sleep is a method of thread class (thread) that causes this thread to suspend execution for a specified period of time, giving the execution an opportunity to another thread, but the monitoring State is still maintained and will be restored automatically. Calling sleep does not release object locks.

Wait is a method of the object class, which invokes the wait method on this object, causing this thread to discard the object lock, enter the waiting lock pool for this object, and only after the Notify method (or Notifyall) is emitted for this object will the thread enter the object lock pool to get the object lock into operation. (If the variable is declared as volatile, it will be consistent with main memory on each visit, and if the variable is accessed in the synchronization method or in the synchronization block, the variable is synchronized when the lock is obtained at the entrance of the method or block and when the lock is released by the method or block exit.) )

Http://www.yjbys.com/news/202750.html

The client program gets the specific container role first, and then the specific iterator role is obtained through the specific container role

Iterator it=new arraylist.iterator ();

1 accesses the contents of a container object without exposing its internal representation.

2) supports multiple traversal of container objects.

3 provides a unified interface (polymorphic iteration) for traversing different container structures.

The constructor was invoked using the New keyword}→

Using the class class's Newinstance method}→ the constructor

The constructor was invoked using the Newinstance method of the constructor class}→

Using the Clone method}→ does not call the constructor

Using deserialization}→ does not call the constructor

 
 

Or

Employee emp2 = Employee.class.newInstance ();
Constructor constructor = Employee.class.getConstructor (); 
Employee Emp3 = Constructor.newinstance ();

Using the Clone method, we need to implement the Cloneable interface first and implement its defined clone method

Employee Emp4 = (employee) emp3.clone ();

When the program is started, it will not load all the class files used by the program at one time, but according to the needs of the program, the Java class loading mechanism (ClassLoader) can dynamically load a class file into memory, so that only the class file is loaded into memory, To be referenced by another class. So ClassLoader is used to dynamically load class files into memory.

Bootstrap ClassLoader: called the Boot class loader, is the top-level class loader in the Java class loading hierarchy, and is responsible for loading the core class libraries in the JDK, such as: Rt.jar, Resources.jar, Charsets.jar, etc. extension ClassLoader: called the Extended class loader, is responsible for loading Java Extensions Class library, the default load java_home/jre/lib/ext/all jars.

App ClassLoader: called the System class loader, is responsible for loading all the jar and class files in the application Classpath directory.

Because this avoids repeated loading, when the father has loaded the class, there is no need to classloader the load again.

For security reasons, let's imagine that if we don't use this delegate pattern, we can use a custom string to dynamically override the types defined in the Java Core API, so there's a very large security risk, and the way the parents delegate can avoid that, Because string is already loaded at startup by the Boot class loader (BOOTSTRCP ClassLoader), the user-defined ClassLoader can never load a string that is written by itself. Unless you change the default algorithm for ClassLoader search classes in the JDK.

1, Request object client requests, this request will contain the parameters from the Get/post request through it to understand the customer's needs, and then respond.

2, the response object to respond to customer requests for information

3. Session object It refers to a client-server conversation that starts with a webapplication from the client to the server until the client disconnects from the server.

4, out object It is an instance of the JspWriter class, is the output to the client commonly used objects

5, Page object it refers to the current JSP page itself, somewhat like the this pointer in the class, it is an instance of the Java.lang.Object class

6, Application object It realizes the sharing of data among users, and can store global variables. It starts at the start of the server until the server shuts down

7, exception object It is an exception object, when a page in the process of the exception occurred, the object is generated.

8. PageContext object It provides access to all objects and namespaces within a JSP page

9, config object It is when a servlet initializes, the JSP engine passes it the information

JS has a function isNaN (val)//If the number is returned false

XMLDOM parsing, Sax parsing, Stax parsing

XMLDOM: (Xmldocumentobjectmodel) The performance of large files is degraded very badly. This problem is caused by the DOM tree structure, which consumes more memory and the DOM must load the entire document into memory before parsing the file, which is suitable for random access to XML;

SAX: (simpleapiforxml) differs from Dom,sax as an event-driven XML parsing method. It reads the XML file sequentially and does not need to load the entire file at once. When you encounter the beginning of a file, the end of the document, or the beginning of the tag and the end of the tag, it triggers an event that the user can use to process the XML file by writing the processing code in its callback event, which is suitable for sequential access to the XML;

StAX: (Streamingapiforxml) differs from other methods in that the application can handle XML as an event flow, regardless of performance or availability, which is superior to other methods;

Thread.getstate ()

The above is a small compilation of questions about the Java interview, I hope to help you, if you have any questions welcome to my message, small series will promptly reply to everyone!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.