How to implement a queue using an array?
When using an array to implement a queue, we must pay attention to the overflow phenomenon. In this case, we can use the method of looping the array to solve it, that is, connecting the ends of the array. Use the front pointer to point to the first position of the queue and the tail pointer to point to the last position of the queue. (Recommended study: java common interview questions)
When an internal class accesses a local variable, why must the variable be modified with final?
Because the life cycle is different. Local variables will be destroyed after the method ends, but the inner class object will not necessarily be destroyed. This will cause the inner class to reference a variable that does not exist.
So the compiler will generate a copy of the local variable in the inner class. The life cycle of this copy is the same as the inner class object, so the above problems will not occur.
But this leads to the problem that one of the variables is modified and the values ??of the two variables may be different. In order to solve this problem, the compiler requires that local variables need to be final modified to ensure that the two variables have the same value.
After JDK8, the compiler does not require that local variables accessed by inner classes must be final modified, but the value of local variables cannot be modified (either in a method or in an inner class), otherwise a compilation error will be reported. Using javap to view the compiled bytecode, you can find that the compiler has added final.
long s = 499999999 * 499999999 In the above code, what is the value of s?
According to the calculation result of the code, the value of s should be -1371654655. This is because the calculation of the right-hand value in Java defaults to the int type.
Can non-static inner classes define static methods?
public class OuterClass{ private static float f = 1.0f; class InnerClass{ public static float func(){return f;} } }
The above code will cause a compilation error, because only static inner classes can define static methods.
What is the difference between Lock and Synchronized?
1. 使用方法的區(qū)別 - **Synchronized**:在需要同步的對象中加入此控制,`synchronized`可以加在方法上,也可以加在特定代碼塊中,括號中表示需要鎖的對象。 - **Lock**:需要顯示指定起始位置和終止位置。一般使用`ReentrantLock`類做為鎖,多個線程中必須要使用一個`ReentrantLock`類做為對象才能保證鎖的生效。且在加鎖和解鎖處需要通過`lock()`和`unlock()`顯示指出。所以一般會在`finally`塊中寫`unlock()`以防死鎖。 2. 性能的區(qū)別 `synchronized`是托管給JVM執(zhí)行的,而`lock`是java寫的控制鎖的代碼。在Java1.5中,`synchronize`是性能低效的。因為這是一個重量級操作,需要調用操作接口,導致有可能加鎖消耗的系統(tǒng)時間比加鎖以外的操作還多。相比之下使用Java提供的Lock對象,性能更高一些。但是到了Java1.6,發(fā)生了變化。`synchronize`在語義上很清晰,可以進行很多優(yōu)化,有適應自旋,鎖消除,鎖粗化,輕量級鎖,偏向鎖等等。導致在Java1.6上`synchronize`的性能并不比Lock差。 - **Synchronized**:采用的是CPU悲觀鎖機制,即線程獲得的是獨占鎖。獨占鎖意味著 **其他線程只能依靠阻塞來等待線程釋放鎖**。而在CPU轉換線程阻塞時會引起線程上下文切換,當有很多線程競爭鎖的時候,會引起CPU頻繁的上下文切換導致效率很低。 - **Lock**:用的是樂觀鎖方式。所謂樂觀鎖就是,**每次不加鎖而是假設沒有沖突而去完成某項操作,如果因為沖突失敗就重試,直到成功為止**。樂觀鎖實現的機制就是`CAS`操作。我們可以進一步研究`ReentrantLock`的源代碼,會發(fā)現其中比較重要的獲得鎖的一個方法是`compareAndSetState`。這里其實就是調用的CPU提供的特殊指令。 3. `ReentrantLock`:具有更好的可伸縮性:比如時間鎖等候、可中斷鎖等候、無塊結構鎖、多個條件變量或者鎖投票。
How do float variables compare to 0?
There are folat types and double types. The possibility of these decimal types directly equaling 0 when approaching 0 is very small. Generally, they approach 0 infinitely, so = cannot be used. = to judge. It should be judged by |x-0| How to create a new non-static inner class? The inner class must be Outer.Inner a when declared, just like int a. As for the static inner class and the non-static inner class new, there is a difference: Outer.Inner a = new Outer().new Inner() (non-static, there must be an Outer object before the new inner class can be created) Outer.Inner a = new Outer.Inner()(static inner class) Java identifier naming rules Can contain: letters, numbers, $, _ (underscore), cannot start with a number, and cannot be Java keywords or reserved words. What design patterns do you know used in JDK? Decoration mode: java.io Single case mode: Runtime class Simple factory mode: Integer.valueOf method Flyweight mode :String constant pool, Integer.valueOf(int i), Character.valueOf(char c) Iterator mode: Iterator Chain of responsibility mode: ClassLoader’s parent delegation model Interpreter mode: Regular expression java.util.regex.Pattern How ConcurrentHashMap ensures thread safety JDK 1.7 and before: ConcurrentHashMap allows multiple modification operations to be performed concurrently. The key is the use of lock separation technology. It uses multiple locks to control modifications to different parts of the hash table. ConcurrentHashMap uses segments internally to represent these different parts. Each segment is actually a small hash table, and they have their own locks. Multiple modification operations can occur concurrently as long as they occur on different segments. JDK 1.8: Although Segment is retained, its attributes have been simplified just to be compatible with older versions. Use CAS algorithm when inserting: unsafe.compareAndSwapInt(this, valueOffset, expect, update). CAS (Compare And Swap) means that if the value contained in the valueOffset position is the same as the expect value, then update the value of the valueOffset position to update and return true, otherwise it will not update and return false. The key or value is not allowed to be null when inserting It is similar to Java8's HashMap. The bottom layer still consists of an "array" linked list red-black tree; The bottom structure stores TreeBin objects, and Not a TreeNode object; CAS is a well-known lock-free algorithm, so does ConcurrentHashMap have no locks? Of course not, when the hash value is the same as the head node of the linked list, it will still be synchronized and locked, and the linked list will be locked. The difference between Thread.sleep() & Thread.yield()&Thread.wait() Both sleep() and yield() will release the CPU. sleep() can give low-priority threads a chance to execute. Of course, it can also give threads of the same priority and high-priority a chance to execute; yield() can only give threads of the same priority a chance to execute. There is a chance of execution. Thread.sleep and Thread.yield() will not cause the lock behavior to change. If the current thread owns the lock, then Thread.sleep will not let the thread release the lock. If it helps you remember, you can simply think that the lock-related methods are defined in the Object class, so calling Thread.sleep will not affect the lock-related behavior. Thread.sleep and Object.wait will suspend the current thread. For CPU resources, no matter which thread is suspended, it means that it no longer requires CPU execution time. The OS will allocate execution time to other threads. The difference is that after calling wait, other threads need to execute notify/notifyAll to regain the CPU execution time. What is the difference between arraylist and linkedlist? Both ArrayList and LinkedList implement the List interface, but there are some differences between them. (1) ArrayList is a data structure based on an index supported by Array, so it provides random access to elements (2) Compared with ArrayList, inserting, Adding and deleting an element will be faster (3) LinkedList consumes more memory than ArrayList because each node in LinkedList stores the reference of the previous and following nodes The above is the detailed content of Common Java interview questions (with answers). For more information, please follow other related articles on the PHP Chinese website!//用程序表示就是
fabs(x) < 0.00001f

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

There are three common methods to traverse Map in Java: 1. Use entrySet to obtain keys and values at the same time, which is suitable for most scenarios; 2. Use keySet or values to traverse keys or values respectively; 3. Use Java8's forEach to simplify the code structure. entrySet returns a Set set containing all key-value pairs, and each loop gets the Map.Entry object, suitable for frequent access to keys and values; if only keys or values are required, you can call keySet() or values() respectively, or you can get the value through map.get(key) when traversing the keys; Java 8 can use forEach((key,value)->

Optional can clearly express intentions and reduce code noise for null judgments. 1. Optional.ofNullable is a common way to deal with null objects. For example, when taking values ??from maps, orElse can be used to provide default values, so that the logic is clearer and concise; 2. Use chain calls maps to achieve nested values ??to safely avoid NPE, and automatically terminate if any link is null and return the default value; 3. Filter can be used for conditional filtering, and subsequent operations will continue to be performed only if the conditions are met, otherwise it will jump directly to orElse, which is suitable for lightweight business judgment; 4. It is not recommended to overuse Optional, such as basic types or simple logic, which will increase complexity, and some scenarios will directly return to nu.

In Java, Comparable is used to define default sorting rules internally, and Comparator is used to define multiple sorting logic externally. 1.Comparable is an interface implemented by the class itself. It defines the natural order by rewriting the compareTo() method. It is suitable for classes with fixed and most commonly used sorting methods, such as String or Integer. 2. Comparator is an externally defined functional interface, implemented through the compare() method, suitable for situations where multiple sorting methods are required for the same class, the class source code cannot be modified, or the sorting logic is often changed. The difference between the two is that Comparable can only define a sorting logic and needs to modify the class itself, while Compar

The core workaround for encountering java.io.NotSerializableException is to ensure that all classes that need to be serialized implement the Serializable interface and check the serialization support of nested objects. 1. Add implementsSerializable to the main class; 2. Ensure that the corresponding classes of custom fields in the class also implement Serializable; 3. Use transient to mark fields that do not need to be serialized; 4. Check the non-serialized types in collections or nested objects; 5. Check which class does not implement the interface; 6. Consider replacement design for classes that cannot be modified, such as saving key data or using serializable intermediate structures; 7. Consider modifying

To deal with character encoding problems in Java, the key is to clearly specify the encoding used at each step. 1. Always specify encoding when reading and writing text, use InputStreamReader and OutputStreamWriter and pass in an explicit character set to avoid relying on system default encoding. 2. Make sure both ends are consistent when processing strings on the network boundary, set the correct Content-Type header and explicitly specify the encoding with the library. 3. Use String.getBytes() and newString(byte[]) with caution, and always manually specify StandardCharsets.UTF_8 to avoid data corruption caused by platform differences. In short, by

Method reference is a way to simplify the writing of Lambda expressions in Java, making the code more concise. It is not a new syntax, but a shortcut to Lambda expressions introduced by Java 8, suitable for the context of functional interfaces. The core is to use existing methods directly as implementations of functional interfaces. For example, System.out::println is equivalent to s->System.out.println(s). There are four main forms of method reference: 1. Static method reference (ClassName::staticMethodName); 2. Instance method reference (binding to a specific object, instance::methodName); 3.

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

There are three common ways to parse JSON in Java: use Jackson, Gson, or org.json. 1. Jackson is suitable for most projects, with good performance and comprehensive functions, and supports conversion and annotation mapping between objects and JSON strings; 2. Gson is more suitable for Android projects or lightweight needs, and is simple to use but slightly inferior in handling complex structures and high-performance scenarios; 3.org.json is suitable for simple tasks or small scripts, and is not recommended for large projects because of its lack of flexibility and type safety. The choice should be decided based on actual needs.
