[Interview] Java Basics (2)

0. Question outline

One, Java basics

1.2 Method operation

1== 和 Equals的区别,如果重写了Equals()不重写HashCode()会发生什么?

2、Java有个最基本的类Object,这个类默认包含哪几个方法?

3、对比Vector、ArrayList、LinkedList有何区别?【第8讲】(*4- 追问1:是不是线程安全的?
 - 追问2:各自应用场景是什么?

4、对比Hashtable、HashMap、TreeMap有什么不同?【第9讲】(*3)
 - 更多:……
// 接HashMap之追问系列
	1、为什么是 0.75 这个值呢?
	
	2、什么办法来解决因链表过长导致查询时间复杂度高的问题呢?
	
	3、影响 HashMap 性能的因素?
	
	4、HashMap的哈希函数怎么设计的?
	 - 追问1:初始容量为什么设置为 2 的整数次幂?【(n - 1) & hash 】
	 - 追问2:如果没使用 hash() 方法计算 hashCode,直接使用对象的 hashCode 值,会出现什么问题呢?
	 - 追问3:为什么获取下标时用按位与 &,而不是取模 %
	
	5、JDK1.8后对HashMap的改进(*3- 追问1:为什么要做这几点优化?
	 - 追问21.8 中的 HashMap 是否线程安全?
	 - 追问3:什么时机执行 resize()- 追问4resize() 如何实现的?
	
	6、HashMap get和put源码,
	
	7、HashMap 的 key 需要满足什么条件?
	 - 追问1:HashMap 允许 key/value 为 null, 但最多只有一个。 为什么?
	 - 追问2:如果重写了equals(),不重写hashCode()会发生什么?
	
	8、你平常怎么解决这个线程不安全的问题?
	
	9、那你知道ConcurrentHashMap的分段锁的实现原理吗?
5、HashSet底层实现?
 - 追问1:线程安全吗?

6、Java提供了哪些IO方式(*2)? NIO如何实现多路复用?【第11讲】

7、Java有几种文件拷贝方式?哪一种最高效?【第12讲】

8、写正则表达式进行手机号匹配(*2)。

One, Java basics

1. What is the difference between == and Equals?

== : Basic data type: comparison value; reference data type: comparison object (heap) memory address memory.

equals : The default is reference comparison. Many classes (String, Integer) override equals and become value comparisons.

// 举例:
public class StringDemo {
    
    
    public static void main(String args[]) {
    
    
        String str1 = "Hello";
        String str2 = new String("Hello");  // 开辟新的堆内存
        String str3 = str2; // 引用传递
        System.out.println(str1 == str2); // false
        System.out.println(str1 == str3); // false
        System.out.println(str2 == str3); // true
        System.out.println(str1.equals(str2)); // true
        System.out.println(str1.equals(str3)); // true
        System.out.println(str2.equals(str3)); // true
    }
}

2. Java has the most basic class Object. Which methods does this class contain by default?

Function name Features
registerNatives() Register the local method
getClass() Returns the runtime class of an object
hashCode() Returns the hash value of the object
equals() Indicates whether some other object is equal to this object
clone() Create and return a copy of this object
toString() Returns the string representation of the object
notify() Wake up a single thread waiting on this object monitor
notifyAll() Wake up all threads waiting on this object monitor
wait(long) Cause the current thread to wait to call notify() or notifyAll() of this object
wait(long,int) Cause the current thread to wait until other threads call notify() or notifyAll() of this object, or some other thread interrupts the current thread, or a certain amount of actual time has passed
wait() Cause the current thread to wait until other threads call notify() or notifyAll() of this object
finalize() When the garbage collection determines that there are no more references to the object, this method is called by the object's garbage collector
Object() Default constructor

3. What is the difference between Vector, ArrayList and LinkedList? [Lecture 8] (*2): Storage, threads, expansion

Object storage Thread Expansion
Vector Dynamic array Y 100%
ArrayList Dynamic array N 50%
LinkedList Doubly linked list N -
Follow-up 1: What are the respective application scenarios?

Vector and ArrayList are stored sequentially in the form of an array , so they are very suitable for random access .
LinkedList is very efficient for inserting and deleting , but random access is slower than dynamic arrays.

4. What is the difference between Hashtable, HashMap and TreeMap? [Lecture 9] (*6)

HashtableIt is a synchronized hash table implementation and does not support null keys and values . Synchronization makes the overhead more expensive and is rarely used.

HashMapIt is an asynchronous hash table implementation that supports null keys and values, etc. put、getOperations can usually achieve constant- time performance and are the first choice for most key-value pair access.

TreeMapIs based on the red-black tree one providing sequential access to Map, get、put、removetype of operation is the time complexity O(logn), by a specific order 指定Comparator 或 键的自然顺序determined by.

补充:
1、相同:都是 Map 实现,是以键值对形式存储和操作数据的容器类型。
2、容器:存储元素的单元。这样来看,数据类型都是容器。
3、线程同步:多线程操作一个资源导致资源不一致,这需要协调资源的调度,即线程同步。
4、线程安全:多线程访问类X时,X都表现正确行为,则X是线程安全。 线程安全类封装了同步机制。

Follow-up series:

1、为什么是 0.75 这个值呢?

2、什么办法来解决因链表过长导致查询时间复杂度高的问题呢?

3、影响 HashMap 性能的因素?

4、HashMap的哈希函数怎么设计的?
 - 追问1:初始容量为什么设置为 2 的整数次幂?【(n - 1) & hash 】
 - 追问2:如果没使用 hash() 方法计算 hashCode,直接使用对象的 hashCode 值,会出现什么问题呢?
 - 追问3:为什么获取下标时用按位与 &,而不是取模 %

5、JDK1.8后对HashMap的改进(*3- 追问1:为什么要做这几点优化?
 - 追问21.8 中的 HashMap 是否线程安全?
 - 追问3:什么时机执行 resize()- 追问4resize() 如何实现的?

6、HashMap get和put源码,

7、HashMap 的 key 需要满足什么条件?
 - 追问1:HashMap 允许 key/value 为 null, 但最多只有一个。 为什么?
 - 追问2:如果重写了equals(),不重写hashCode()会发生什么?

8、你平常怎么解决这个线程不安全的问题?

9、那你知道ConcurrentHashMap的分段锁的实现原理吗?

For detailed answers, please refer to: [Questions] [Java] HashMap+Interview finishing

5. The underlying implementation of HashSet?

A layer is wrapped on the HashMap, the static constant of an Object is stored by default, and only the key is returned when fetching. The add method calls the put() method of HashMap to implement.

if key is existed, then 是旧值,失败;
if (map.put()==null), then 添加元素作为map.key

Follow-up 1: Is it thread safe?

Not safe, same as HashMap.

6. What IO methods (*2) does Java provide? How does NIO realize multiplexing? [Lecture 11]

There are many Java IO methods, which can be easily distinguished based on different IO abstract models and interaction methods.

First of all, the traditional java.io package, which is implemented based on the stream model, provides some of the most familiar IO functions, such as File abstraction, input and output streams, etc. The interaction method is a synchronous and blocking method. That is to say, when reading an input stream or writing an output stream, the thread will always be blocked until the reading and writing actions are completed, and the calls between them are in a reliable linear sequence.

The advantage of the java.io package is that the code is relatively simple and intuitive, but the disadvantage is that there are limitations in IO efficiency and scalability, which can easily become a bottleneck for application performance.

Many times, people also classify some of the network APIs provided under java.net, such as Socket, ServerSocket, and HttpURLConnection into the synchronous blocking IO library, because network communication is also an IO behavior.

Second, the NIO framework (java.nio package) was introduced in Java 1.4, providing new abstractions such as Channel, Selector, Buffer, etc., which can build multiplexed, synchronous non-blocking IO programs, while providing closer operations High-performance data operation mode at the bottom of the system.

Third, in Java 7, NIO has been further improved, that is, NIO 2, which introduces an asynchronous non-blocking IO method, which is also called AIO (Asynchronous IO) by many people. Asynchronous IO operations are based on events and callback mechanisms. It can be simply understood as that the application operation returns directly without blocking there. When the background processing is completed, the operating system will notify the corresponding thread to perform follow-up work.

7. How many file copy methods does Java have? Which one is the most efficient? [Lecture 12]

Java has a variety of typical file copy implementation methods, such as:

Use the java.io class library to directly construct a FileInputStream for the source file to read, and then construct a FileOutputStream for the target file to complete the writing work.


public static void copyFileByStream(File source, File dest) throws
        IOException {
    
    
    try (InputStream is = new FileInputStream(source);
         OutputStream os = new FileOutputStream(dest);){
    
    
        byte[] buffer = new byte[1024];
        int length;
        while ((length = is.read(buffer)) > 0) {
    
    
            os.write(buffer, 0, length);
        }
    }
 }

Or, use the transferTo or transferFrom method provided by the java.nio class library.


public static void copyFileByChannel(File source, File dest) throws
        IOException {
    
    
    try (FileChannel sourceChannel = new FileInputStream(source)
            .getChannel();
         FileChannel targetChannel = new FileOutputStream(dest).getChannel
                 ();){
    
    
        for (long count = sourceChannel.size() ;count>0 ;) {
    
    
            long transferred = sourceChannel.transferTo(
                    sourceChannel.position(), count, targetChannel);            sourceChannel.position(sourceChannel.position() + transferred);
            count -= transferred;
        }
    }
 }

Of course, the Java standard library itself already provides several implementations of Files.copy.

For the efficiency of Copy, this is actually related to the operating system and configuration. Generally speaking, the NIO transferTo/From method may be faster because it can better utilize the underlying mechanisms of modern operating systems to avoid unnecessary copying and context switching.

8. Write regular expressions to match mobile phone numbers (*2)

# 号码规则:
1、第 1 位: 1
2、第 2 位: 39
3、第 3 到第 11 位只要是数字就行.


答案: /^[1]([3-9])[0-9]{
    
    9}$/

(1) /^ - 表示文本开始;
(2) () - 子表达式的开始与结束;
(3) [] - 要匹配里面内容,[0-9]匹配数字范围为0/1/2/3/4/5/6/7/8/9(4) {
    
    n} - 匹配n次,{
    
    9}是匹配9次;
(5) ^ - 字符串开始,\^ - 匹配 ^ 字符本身; $ - 字符串结束。

Three, reference

1. Java syntax-the difference between equals and == in Java
2. Do you really understand the difference between == and equals?
3. Why rewrite equals() and also rewrite hashCode()
4. The necessity of rewriting hashCode method after rewriting equals method
5. Mobile phone number segment regular expression (2019-01 latest)
6. Regular expression- Syntax
7, [doubts sorting out] [Java] in-depth explanation of HashMap+ interview sorting

Guess you like

Origin blog.csdn.net/HeavenDan/article/details/112728222