Java Interview Preparation

Source: Internet
Author: User
Tags rehash set set wrapper stringbuffer

Write more, but the sense of self is still more practical.

J2SE Foundation:

1. Size of eight basic data types, and their encapsulation classes;

The Java language provides eight basic types. Six numeric types (four integers, two floating-point types), one character type, and one Boolean type.
A), integer: Including Int,short,byte,long
b), floating-point type: float,double
c), character: Char
D), Boolean: Boolean

Basic Categories size Minimum Value Maximum Value Packing class
Boolean ------- ------ ------- Boolean
Char 16-bit Unicode 0 Unicode 2^16-1 Character
Byte 8-bit -128 +127 Byte
Short 16-bit -2^15 +2^15-1 Short
Int 32-bit -2^31 +2^31-1 Integer
Long 64-bit -2^63 +2^63-1 Long
Float 32-bit IEEE754 IEEE754 Float
Double 63-bit IEEE754 IEEE754 Double
Attention. : The ^ in the form represents the second party

More details URL: http://blog.csdn.net/jj___jj/article/details/5589415

2. Switch can use string to do parameters.

In switch (EXPR1), expr1 is an integer expression that can be an int base type or an integer wrapper type, and because Byte,short,char can be implicitly converted to int, these types and the type of wrapper are also possible.   Therefore, the arguments passed to the switch and case statements should be int, short, char or Byte, and enum. Long,string can not act on Swtich.

The switch's parameter type can be a string type in JDK 1.7.

The difference between 3.equals and = =

a). = = is an operator.
b). Equals is the method of the string object, and you can. (point) out.
  
We compare the two kinds of 1, basic data type comparison 2, reference object comparison
A), basic data type comparisons
= = and equals compare two values for equality. Equal to true otherwise false;
  
b), Reference object comparisons
= = and equals are compared to the same address in stack memory. Equal to true otherwise false;
  
Some points to note:
A), string is a special reference type. For a comparison of two strings, both = = and Equals are compared to whether the strings are the same;
b, when you create two string objects, the address in memory is not the same, and you can assign the same value.
So the contents of the string are the same. The reference address is not necessarily the same, (the same object address is not necessarily the same), but the opposite is affirmative;
c), base data type comparison (except string) = = and Equals are both comparison values;

4.Object What are the common methods;

object is the parent class of all classes, and any class inherits object by default.
Clone
The protection method, realizes the object the shallow duplication, only then realizes the Cloneable interface may call this method, otherwise throws the Clonenotsupportedexception exception
equals
In object, as = = is the same, subclasses generally need to override this method
Hashcode
This method is used for hashing lookups, and overriding the Equals method generally overrides the Hashcode method. This method is used in some collection with hash functions.
GetClass
Final method, get Run-time type
Wait
Causes the current thread to wait for the lock on the object, and the current thread must be the owner of the object, that is, the lock with the object. The wait () method waits until a lock is obtained or is interrupted. Wait (long timeout) sets a time-out interval that is returned if the lock is not obtained within the specified time.
When this method is invoked, the front thread goes to sleep until the following events occur:
a). Other threads call the Notify method of the object
b). Other threads call the Notifyall method of the object
c). Another thread called the interrupt interrupt the thread
D). The time interval is up.
At this point, the thread can be scheduled, and if it is interrupted, throw a interruptedexception exception
Notify
Wake up a thread waiting on the object
Notifyall
Wakes up all threads waiting on the object
Tostring
Conversion to a string, the general subclass has to rewrite, otherwise print handle 5.java four kinds of references, weak soft virtual, the use of the scene;
Content more can own Baidu, in fact LZ also not very clear ...
The role of 6.Hashcode;
First of all, to understand the role of hashcode, you have to know the collection in Java first.
In general, the set in Java (Collection) has two classes, one is list, and the other is set. Do you know the difference between them? The elements in the former set are ordered, the elements can be duplicated, the latter elements are unordered, but the elements cannot be duplicated. So here is a more serious problem: to ensure that the elements do not repeat, can two elements of repetition should be based on what to judge. This is the Object.Equals method. However, if each additional element is checked once, the number of elements that are added to the collection is much more frequent when the elements are many. That is, if there are now 1000 elements in the collection, then the 1001th element will call the Equals method 1000 times when it joins the collection. This will obviously greatly reduce efficiency.
As a result, Java uses the principle of a hash table. Hash is actually a personal name, and since he proposes the concept of a hashing algorithm, it is named after him. Hash algorithms, also known as hashing algorithms, are used to assign data directly to an address according to a specific algorithm. If the hashing algorithm is explained in detail, it will require more space for the article, I will not introduce it here. Beginners can understand that the Hashcode method actually returns the physical address of the object store (which may not actually be).
This way, when the collection wants to add a new element, it first calls the Hashcode method of the element, and then it can navigate to the physical location where it should be placed. If there are no elements in this position, it can be stored directly in this position, no more comparisons are made, and if there is already an element in the position, the Equals method of calling it is compared to the new element, and the same is not saved, and the other addresses are hashed out. So there is a problem of conflict resolution here. The number of actual calls to the Equals method is greatly reduced, almost one or two times.
So, Java for the Eqauls method and the Hashcode method is this stipulation:
A), if two objects are the same, then their hashcode values must be the same;
b), if two objects have the same hashcode, they are not necessarily the same
The object mentioned above refers to the comparison with the Eqauls method.
You can of course not do it as requested, but you will find that the same object can appear in the set set. At the same time, the efficiency of adding new elements will be greatly reduced.
7. Differences in Arraylist,linkedlist,vector;
A) thread safety:
Vector, Stack: thread safety;
ArrayList, LinkedList: not thread safe.
b) Ways to achieve:
LinkedList: bidirectional linked list;
Arraylist,vector,stack: Array.
c) Capacity expansion aspects:
Because the ArrayList and vector (stack inherits from the vector, only several stack-related methods are added on the vector basis), the stack does not have to be specifically described after that, using an array implementation that creates a larger array inside when the array is not long enough. The data in the original array is then copied to the new array. For expansion, expand at least 2 + 1 at a time, if the vector is created without specifying the value of the capacityincrement (automatically extended length), or at least twice times the original length if you want to extend it, each time you extend it at the *3 length.
8. The difference between String,stringbuffer,stringbuilder:
string is a string constant, StringBuffer is thread-safe and StringBuilder is thread-safe.
A) Stirng: string constant, string length immutable. In Java, a string is immutable (immutable).
b) StringBuffer: String variable (Synchronized, that is, thread-safe). If you want to frequently modify the contents of a string, it is best to use stringbuffer for efficiency reasons, and you can call the StringBuffer () method if you want to convert to a string type.
c) StringBuilder: String variable (not thread safe). Internally, the StringBuilder object is treated as a variable-length array that contains a sequence of characters.
Java.lang.StringBuilder is a variable sequence of characters that is added to JDK5.0. This class provides an API that is compatible with StringBuffer, but does not guarantee synchronization. This class is designed as a simple replacement for stringbuffer, which is common when a string buffer is used by a single thread.
Main differences:
The main performance difference between string type and StringBuffer: String is an immutable object, so each time a change is made to the string, a new string object is generated and the pointer is pointed to a new string object. So it is best not to use string to change the content frequently, because each build object will have an impact on the system performance, especially when there are no more references in memory, the JVM's GC will begin to work, and it will be degraded.
When using the StringBuffer class, the StringBuffer object itself is manipulated each time, rather than generating new objects and altering the object reference. Therefore, it is recommended that stringbuffer be used in most cases, especially where string objects are often changed.
In some special cases, string concatenation of a string object is actually compiled by the Java Compiler into a concatenation of StringBuffer objects, so the speed of the string object is not slower than the StringBuffer object.
Use Policy:
A The basic principle: if you want to manipulate a small amount of data, using string, single-threaded operation of large amounts of data, using StringBuilder multithreading to manipulate large amounts of data, using StringBuffer.
b Do not use the String class "+" for frequent stitching, because the performance is very poor, should use the StringBuffer or StringBuilder class, this is a more important in Java optimization principle.
C For better performance, you should specify their capacity whenever possible when constructing stirngbuffer or Stirngbuilder. Of course, if you're working with a string length of no more than 16 characters, you don't need to do that, and when you do not specify a capacity (capacity), the default is to construct an object with a capacity of 16. Not specifying capacity can significantly degrade performance.
D StringBuilder generally used within the method to complete a similar "+" function, because the thread is not safe, so you can discard after use. StringBuffer is mainly used in global variables.
E The use of stirngbuilder in the same situation can only be achieved by using StringBuffer to achieve a performance boost of 10%~15%, but it risks multiple thread insecurity. In the real-world modular programming, the programmer in charge of a module is not necessarily able to determine clearly whether the module will be put into a multithreaded environment, so: unless you determine that the system bottleneck is on the stringbuffer, and that your module will not run in multithreaded mode, Can use the StringBuilder, otherwise still use StringBuffer.

Features and usage of 9.MAP, Set, List, Queue, Stack:
Map

The map is a key-value pair, the key is the only one that cannot be duplicated, a key corresponds to a value, and the value can be duplicated.
TreeMap can guarantee order, HashMap not guarantee order, that is disorderly.
The map can extract key and value separately, where the keyset () method extracts all keys to a set. The values () method extracts all values in a map into a single collection. Set

Does not contain a collection of repeating elements, and a set contains up to a null element
Only single traversal can be implemented with Lterator, and there is no synchronization method in set. List

An ordered, repeatable collection.
You can add deletion elements in any location.
Using iterator to achieve one-way traversal, but also can be listiterator to achieve bidirectional traversal Queue

The queue complies with the advanced first out principle.
When used, try to avoid the add () and remove () methods, but instead use an offer () to add elements, use poll () to remove elements, its advantage is that the return value to determine whether the success.
LinkedList implements the queue interface.
Queue is not normally allowed to insert null elements.

Stack
The stack complies with the LIFO principle.
Stack inherits from Vector.
It extends the class vector through five operations, allowing the vector to be considered a stack, which provides the usual push and pop operations, and the Peek () method that takes the stack vertex, the empty method of whether the test stack is empty, and so on

Usage

If you are involved in stacks, queues, and other operations, the list is recommended
For quickly inserting and deleting elements, it is recommended that you use LinkedList
If you need to quickly randomly access elements, it is recommended that you use Arraylis
The difference between HashMap and Hashtable:

let's look at the definition of 2 classes first.

  public class Hashtable  
    extends Dictionary  
    implements Map, Cloneable, java.io.Serializable 

  public class HashMap  
    extends Abstractmap  
    implements Map, Cloneable, Serializable  

Visible Hashtable inherits from Dictiionary and HashMap inherits from Abstractmap

Hashtable's Put method is as follows
Public synchronized V-put (K key, V value) {//###### Note here 1 02.  Make sure the ' value is ' not null 03.    if (value = = null) {//###### Note here 2 04.  
throw new NullPointerException ();  05.} 06.  
Makes sure the ' key is ' not ' already in the Hashtable.  
Entry tab[] = table; an int hash = Key.hashcode ();  ###### Note here 3 09.  
int index = (hash & 0x7fffffff)% Tab.length;    for (Entry e = Tab[index]; e!= null; e = e.next) {11.      if (E.hash = hash) && E.key.equals (key) {12.  
V old = E.value;  
E.value = value;  
return old;  15.} 16.  } 17.  
modcount++;    if (count >= threshold) {19.    Rehash the table if the threshold is exceeded 20.  
Rehash ();  
tab = table;  
Index = (hash & 0x7fffffff)% Tab.length;  23.} 24.  
Creates the new entry.  
Entry e = Tab[index];  
Tab[index] = new Entry (hash, key, value, E);  
count++;  
return null; 
 29.}
Note that the 1 method is synchronized
Note that the 2 method does not allow Value==null
Note that the 3 method calls the Hashcode method of the key and, if key==null, throws a null pointer exception HashMap The PUT method as follows
Public V-Put (K key, V value) {//###### Note here 1  
.  if (key = = null)  //###### note here 2  
.    return Putfornullkey (value);  int hash = hash (Key.hashcode ());  
A.  int i = indexfor (hash, table.length);  
For  (Entry e = table[i]; e!= null; e = e.next) {  
modified.    Object K;  
An.    if (E.hash = = Hash && ((k = e.key) = = Key | | key.equals (k))) {  
.      V oldValue = e.value;      e.value = value;      e.recordaccess (this);  
return      OldValue;  
.  }  modcount++;  addentry (hash, key, value, I);  ###### notice here   
.  return null;  
18.}  
Note that the 1 method is unsynchronized
Note that the 2 method allows key==null
Note that the 3 method does not make any calls to value, so allow null
Add:
Hashtable has a contains method, easy to cause misunderstanding, so in HashMap has been removed
Of course, all 2 classes use ContainsKey and Containsvalue methods.

HashMap Hashtable

Parent class Abstractmap Dictiionary

whether synchronization is

k,v can null or not

HashMap are lightweight implementations of Hashtable (not thread-safe implementations), they all complete the map interface,

The main difference is that HASHMAP allows null (NULL) key values (keys), which may be more efficient than hashtable due to the fact that it is not thread safe. HashMap allows NULL to be used as a entry key or value, and Hashtable is not allowed.

HashMap the Hashtable contains method removed, changed to Containsvalue and ContainsKey. Because the contains method is easy to cause misunderstanding.

Hashtable inherits from the dictionary class, and HashMap is an implementation of the map interface introduced by Java1.2.

The biggest difference is that the Hashtable method is synchronize, and HashMap is not, when multiple threads access Hashtable, they do not need to synchronize their methods, and HashMap must provide an external synchronization ( COLLECTIONS.SYNCHRONIZEDMAP).

Hashtable and HashMap adopt the Hash/rehash algorithm are probably the same, so there is no significant difference in performance.






















Related Article

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.