Thank you for your reference!
Http://www.blogjava.net/fanyingjie/archive/2007/06/27/126467.aspx
Http://baike.baidu.com/view/1788559.htm
Http://honda418.iteye.com/blog/315893
Http://jeff-tang.blog.163.com/blog/static/141686909201022010522906/
Http://www.cnblogs.com/mgod/archive/2007/08/05/844011.html
Referenced books
Deep understanding of Java Virtual Machine: Advanced JVM features and best practices
12. Differences between arraylist, vector, and sorted list
|
Arraylist |
Vector |
Shortlist |
Implementation Principle |
Array |
Array |
Two-way linked list |
Thread Security |
No |
Yes |
No |
Advantages |
1. array implementation is better than Traversal 2. Non-thread security and High Efficiency |
1. array implementation is better than Traversal 2. Thread Security |
1. Addition and deletion of nodes without reconstruction of Objects 2. No waste of space |
Disadvantages |
1. Non-thread security 2. Unused elements in the array are a waste of space. 3. Resizing may cause object Reconstruction 4. addition or deletion may cause the movement of array elements |
1. Space waste caused by unused elements in the array 2. Resizing may cause object Reconstruction 3. thread security and low efficiency 4. addition or deletion may cause the movement of array elements |
1. Low traversal Efficiency 2. Non-thread security |
Resizing |
0.5 multiplied |
1 multiplied |
Add or delete as needed |
Use Cases |
1. wireless connection requirements. 2. More traversal and less addition and Deletion |
1. thread security requirements 2. There are many traversal scenarios and few addition/deletion scenarios. |
When there are many Add/delete scenarios |
Differences between 11.int and integer
|
Int |
Integer |
Type |
Basic Type |
Composite Type |
Default Value |
0 |
Null |
Storage |
Stack (local variable) Heap (member variable, to be further confirmed) |
Stack (only created through new) |
Method |
No method for basic type |
Yes |
Speed |
Fast (stack operations are relatively fast) |
Slow |
Generic support |
No (the generic type in Java is not supported, and the template in C ++ is supported) |
Supported |
Container support |
No (usually packing is performed directly) |
Supported |
Meaning |
1. historical reasons (C/C ++ is postponed) 2. convenient and fast (New is not required) |
Packaging class of basic type int Provides support for generic and container classes |
9. Add a String object to a list <integer> container.
Knowledge needed
- In Java, generics are pseudo generics. (See Zhou Zhiming's in-depth understanding of Java Virtual Machine: JVM advanced features and Best Practices.)
- Generics are the syntactic sugar of the compiler, rather than the actual type list <integer>.
- Both list <integer> and list <string> are compiled and used as the list <Object> type.
- There is no generic concept in Java virtual machines.
- Through reflection, some mandatory checks can be postponed to the runtime.
- If you insert a String object directly to list <integer>, the compiler will check the object and prompt an error.
- The reflection mechanism can delay the check of such errors to the runtime. (This is a drawback of reflection. It will delay the issue that can be checked during the compilation period until it reaches the runtime)
- Because the list <integer> object exists in the form of list <Object> during runtime, no errors will be generated during runtime.
- Reflection mechanism, through the check during the compilation period cheated us. In addition, we can pass the compiler check through reflection.
Implementation Code
Package COM. jue. test; import Java. lang. reflect. invocationtargetexception; import Java. lang. reflect. method; import Java. util. arraylist; import Java. util. list; public class testmain {list <integer> mintlist = new arraylist <integer> (); public static void main (string [] ARGs) throws securityexception, nosuchfieldexception, illegalargumentexception, illegalaccessexception, invocationtargetexception, nosuchmethodexception {testmain TM = new testmain (); Method addmethod = List. class. getmethod ("add", new class [] {object. class}); // use reflection to avoid the forced check addmethod during the compilation period. invoke (TM. mintlist, new object [] {New String ("ABC")}); addmethod. invoke (TM. mintlist, new object [] {New String ("123")}); addmethod. invoke (TM. mintlist, new object [] {New String ("CDE")}); addmethod. invoke (TM. mintlist, new object [] {New String ("fgh")}); For (Object O: TM. mintlist) {system. out. println (o );}}}
Output result:
ABC
123
CDE
Fgh
10. List <integer> and list <string> both exist in the form of list <Object> after compilation.
package com.jue.test;import java.util.List;public class TestMain {public void testList(List<Integer> list) {}public void testList(List<String> list) {}}
Result: compilation failed!
Analysis:
- As mentioned above, Java generics are the syntactic sugar of the compiler. After compilation, they are all replaced by list <Object>.
- For overload, the same name is used, and the signature is different. Because the parameters are both list <Object>, compilation fails because it is impossible to generate two methods with the same signature.
1. Short conversion related
First,
package com.jue.test;public class TestMain { public static void main(String args[]){ short s1 = 1; s1 = s1 + 1; }}
Compilation result
Description resourcepathlocationtype
Type Mismatch: cannot convert from int to short
Testmain. Java/testshort/src/COM/Jue/testline 6 Java Problem
Analysis:
S1 + 1 is automatically converted to int type, resulting in S1 = S1 + 1; loss of precision.
Second,
package com.jue.test;public class TestMain {public static void main(String args[]){short s2 = 2;s2 += 2;}}
Compilation result: Successful
Analysis:
After Decompilation
package com.jue.test;public class TestMain{ public static void main(String[] args) { short s2 = 2; s2 = (short)(s2 + 2); }}
Therefore, it may be the syntactic sugar of the Java compiler.
2. The difference between runtimeexception and common exception and error.
Checked exception: it can be detected by the Java compiler during compilation.
Uncheckedexception: during compilation, the Java compiler cannot check.
|
Runtimeexception |
Normal exception |
Error |
Controlled exception |
No |
Yes |
No |
Cause |
Developer programming error |
Due to external environment limitations, Potential problems |
System Errors During Java runtime and resource depletion are serious, Problems that cannot be fixed by the program |
Example |
Nullpointerexception Arrayoutofindexexception Classcastexception Arithmeticexception Unsupportedoperationexception |
Classnotfoundexception Ioexception Filenotfoundexception |
Virtualmachineerror Stackoverflowerror Outofmemoryerror |
3. A finally interview question
package com.jue.test;import java.util.ArrayList;import java.util.List;public class TestMain {public static void main(String[] args) {test();}private static void test() {List list = new ArrayList();try {System.out.println("return!!");return;} catch (Exception e) {System.out.println("catch Exception !!");} finally {System.out.println("finally!!");}}}
Result:
Return !!
Finally !!
Analysis: Even if return; finally is always executed in try, it will still be executed.
4. Differences between final, finalize, and finally
Final: keyword, table unchanged
Modifier:
- Method: The method cannot be override.
- Class: cannot be inherited
- Basic Type: constant, value immutable
- Conformity type: the reference value is unchangeable.
final Object o1 = new Object();o1 = new Object();
Finally: keyword, part of the Java Exception Handling Mechanism, used to provide a necessary opportunity to clean up when an exception occurs.
Finalize: object class method (refer to Baidu encyclopedia)
Meaning: Java technology allows you to use the finalize () method to clear objects before the Garbage Collector recycles them.
Prerequisites: This object is definitely not referenced.
Working principle:
- The garbage collector is ready to release the space occupied by objects.
- First, call its Finalize method.
- Memory is actually recycled during the next garbage collection process.
Uncertainty:
- The execution time of finalize is unlimited.
- When one object references another object, the Finalize method cannot follow the specific execution order.
5. Override, overload
|
Override |
Overload |
Signature + Return Value |
Same |
The method name is the same and the signature is different. |
Link |
Parent-Child inheritance |
Usually in the same class hierarchy |
Recognition |
Runtime polymorphism Based on the specific object, Query the virtual method table of an object and determine the call relationship. |
Polymorphism during compilation Determined by the appearance type of the object (that is, the declared type) |
Modifier limit |
Non-Private Non-static Non-Final |
No special |
Abnormal relationship |
The subclass method cannot throw more exceptions of the parent class method. |
No special |
Visibility relationship |
The sub-class cannot have a lower access permission than the parent class. (Decided by the Lee's replacement principle) |
No special |
6. Collection collections
Collection: interface, Collection class interface, a contract, provides the basic size of the Set, add, clear, traverse method, and so on.
Collections: A Tool class that provides many static methods for the set, such as query, comparison, sorting, switching, and thread security.
7. Integer Cache
package com.jue.test;public class TestMain {public static void main(String[] args) {Integer i1 = 1;Integer i11 = 1;System.out.println(i1 == i11);Integer i2 = 200;Integer i22 = 200;System.out.println(i2 == i22);}}
Result:
True
False
Analysis: The Decompilation result is
package com.jue.test;import java.io.PrintStream;public class TestMain{ public static void main(String[] args) { Integer i1 = Integer.valueOf(1); Integer i11 = Integer.valueOf(1); System.out.println(i1 == i11); Integer i2 = Integer.valueOf(200); Integer i22 = Integer.valueOf(200); System.out.println(i2 == i22); }}
It can be seen that the compiler has performed additional processing on Integer I = 1, that is, integer. valueof ();
Integer source code
public static Integer valueOf(int i) {assert IntegerCache.high >= 127;if (i >= IntegerCache.low && i <= IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)];return new Integer(i);}
It can be seen that integer is obtained from the cache for numbers within a certain range. For additional numbers, call New to create.
The source code of integercache is as follows:
private static class IntegerCache {static final int low = -128;static final int high;static final Integer cache[];static {// high value may be configured by propertyint h = 127;String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");if (integerCacheHighPropValue != null) {int i = parseInt(integerCacheHighPropValue);i = Math.max(i, 127);// Maximum array size is Integer.MAX_VALUEh = Math.min(i, Integer.MAX_VALUE - (-low));}high = h;cache = new Integer[(high - low) + 1];int j = low;for (int k = 0; k < cache.length; k++)cache[k] = new Integer(j++);}private IntegerCache() {}}
Therefore, we can know the integer size. The default value is from-128 to 127, and the array in this range is cached.
8. Differences between sleep and wait Methods
|
Wait |
Sleep |
Class |
Object |
Thread |
Meaning |
Thread Suspension |
Specifies the time for the thread to sleep |
Release lock |
Yes |
No (this has nothing to do with the lock) |
Restore |
1. Parameter: Wait specified time 2. No parameter: Wait for other threads to submit y |
1. Automatic recovery based on the parameter length. 2. Exception interruption |
Limits |
Wait, policy must be called when the current object lock is held |
No special |
Throw an exception |
No |
Yes |
Static Method |
No |
Yes |