当前位置:网站首页>Basic grammar of interview (Part 2)
Basic grammar of interview (Part 2)
2022-07-03 17:31:00 【J.King】
Method
Why static methods cannot call non static members ?
This needs to be combined with JVM Knowledge about , The main reasons are as follows :
- Static methods belong to classes , Memory is allocated when the class is loaded , It can be accessed directly through the class name . The non static members belong to instance objects , Only after the object is instantiated , You need to access... Through the instance object of the class .
- Static members exist when non static members of a class do not exist , Call a non static member that does not exist in memory , It's illegal
How is the static method different from the instance method ?
1、 Call mode
When a static method is called externally , have access to Class name . Method name The way , You can also use object . Method name The way , And the instance method only has the latter way . in other words , You can call static methods without creating objects .
2、 Whether there are restrictions on accessing class members
Static methods when accessing members of this class , Only static members are allowed ( Static member variables and static methods ), Access to instance members is not allowed ( Instance member variables and instance methods ), The instance method does not have this limitation .
The difference between overloading and rewriting
Overloading is the same method that can be used depending on the input data , Make a different deal
Overriding is the same method that a subclass inherits from its parent , The input data is the same , But to make a response different from the parent class , You're going to override the parent method
heavy load (Overloading)
Occurs in the same class ( Or between a parent class and a child class ), Method name must be the same , Different parameter types 、 The number is different. 、 Different order , Method return values and access modifiers can be different .
《Java The core technology 》 This book introduces overloading :
If multiple methods ( such as
StringBuilderConstruction method of ) Have the same name 、 Different parameters , It creates a heavy load .StringBuilder sb = new StringBuilder(); StringBuilder sb2 = new StringBuilder("HelloWorld");The compiler has to pick out which method to execute , It selects the corresponding method by matching the parameter type given by each method with the value type used by the specific method call . If the compiler cannot find a matching parameter , A compile time error occurs , Because there's no match at all , Or none is better than the others ( This process is called overload parsing (overloading resolution)).
Java Allow any method to be overloaded , It's not just the constructor method .
Sum up : Overloading means that the same method name in a class handles different logic according to different parameter lists .
rewrite
Rewriting occurs at run time , Is a subclass to the parent class to allow access to the method of the implementation process to be rewritten .
- Method name 、 The parameter list must be the same , The return value type of subclass method should be smaller or equal than that of parent method , Exception range thrown is less than or equal to parent class , The access modifier range is greater than or equal to the parent class .
- If the parent method access modifier is
private/final/staticThen the subclass cannot override the method , But bestaticModified methods can be declared again . - Constructor cannot be overridden
Sum up : Rewriting is a modification of the parent method by a subclass , The external appearance cannot be changed , Internal logic can change .
| Difference point | Overloading methods | Rewriting methods |
|---|---|---|
| Range of occurrence | Same class | Subclass |
| parameter list | Must be modified | It must not be modified |
| Return type | Modifiable | The return value type of subclass method should be smaller or equal than that of parent method |
| abnormal | Modifiable | The exception class thrown by the subclass method declaration should be smaller or equal to the exception class thrown by the parent method declaration ; |
| Access modifier | Modifiable | There must be no stricter restrictions ( Can reduce the limit ) |
| The occurrence stage | Compile time | The run-time |
Method overrides are to be followed “ Two are the same, two are small and one is big ”( The following is an excerpt from 《 insane Java The notes 》):
- “ With two ” That is, the method name is the same 、 The parameter list is the same ;
- “ Two small ” This means that the return value type of a subclass method should be smaller or equal than that of a parent method , The exception class thrown by the subclass method declaration should be smaller or equal to the exception class thrown by the parent method declaration ;
- “ A large ” This means that the access rights of subclass methods should be greater or equal than those of parent methods .
️ About Overridden return value type I need to add a little bit more , The above statement is not very clear and accurate : If the return type of the method is void And basic data types , The return value cannot be modified when it is rewritten . But if the return value of a method is a reference type , When overridden, you can return subclasses of the reference type .
public class Admin {
public String name() {
return " Super administrator ";
}
}
public class SuperAdmin extends Admin{
@Override
public String name() {
return " Administrators ";
}
public Hero hero() {
return new Hero();
}
}
public class SuperSuperAdmin extends SuperAdmin {
public String name() {
return " Super super administrator ";
}
@Override
public SuperAdmin hero() {
return new SuperAdmin();
}
}
== and equals() The difference between
== For basic types and reference types, the effect is different :
- For basic data types ,
==Compare values . - For reference data types ,
==Compare the memory address of the object .
because Java Only value passing , therefore , about == Come on , Regardless of the basic data type , Or variables that reference data types , The essence of comparison is value , Only the value of the reference type variable is the address of the object .
equals() Variables that cannot be used to determine the basic data type , It can only be used to judge whether two objects are equal .equals() Methods exist in Object Class , and Object Class is the direct or indirect parent of all classes .
Object class equals() Method :
public boolean equals(Object obj) {
return (this == obj);
}
equals() There are two uses of the method :
- Class does not cover
equals()Method : adoptequals()When comparing two objects of this class , It's equivalent to passing “==” Compare the two objects , The default used isObjectclassequals()Method . - Class covers
equals()Method : We usually coverequals()Method to compare whether properties in two objects are equal ; If their properties are equal , Then return to true( namely , Think these two objects are equal ).
for instance :
String a = new String("ab"); // a For a quote
String b = new String("ab"); // b For another reference , Object has the same content
String aa = "ab"; // Put in constant pool
String bb = "ab"; // Find from constant pool
System.out.println(aa == bb);// true
System.out.println(a == b);// false
System.out.println(a.equals(b));// true
System.out.println(42 == 42.0);// true
String Medium equals The method is rewritten , because Object Of equals Method is to compare the memory address of the object , and String Of equals The method compares the value of the object .
When creating a String When an object of type , The virtual machine looks in the constant pool for objects that have the same existing value as the value to be created , If so, assign it to the current reference . If not, recreate one in the constant pool String object .
String class equals() Method :
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
hashCode() And equals()
The interviewer may ask you :“ You've rewritten it hashCode() and equals() Well ? Why rewrite equals() Must rewrite hashCode() Method ?”
A very basic question , The top priority in the interview , However , Many job seekers still fail to reach their ideas .
# hashCode() What's the usage? ?
hashCode() To get hash code (int Integers ), Also known as hash code . The function of this hash code is to determine the index position of the object in the hash table .
hashCode() It's defined in JDK Of Object Class , That means Java Any class in contains hashCode() function . Another thing to note : Object Of hashCode() Methods are local methods , Also is to use C Language or C++ Realized , This method is usually used to convert the memory address of the object into an integer and return .
public native int hashCode();
Hash table stores key value pairs (key-value), It is characterized by : According to “ key ” Quickly retrieve the corresponding “ value ”. So hash code is used !( You can quickly find the object you need )
# Why would there be hashCode?
We use “HashSet How to check for duplicates ” Give an example of why there should be hashCode?
Here's an excerpt from 《Head First Java》:
When you add objects
HashSetwhen ,HashSetThe object will be calculated firsthashCodeValue to determine where the object is added , At the same time, it will also work with other added objectshashCodeComparison of values , If there is no matchhashCode,HashSetIt assumes that the object does not recur . But if you find the samehashCodeValue object , This will callequals()Methods to checkhashCodeAre equal objects really the same . If they are the same ,HashSetIt won't make the join operation successful . If it's different , It will be re hashed to other locations .. In this way, we will greatly reduceequalsThe number of times , Accordingly, the execution speed is greatly improved .
Actually , hashCode() and equals() Are used to compare whether two objects are equal .
What then? JDK We also need to provide these two methods at the same time ?
This is because in some containers ( such as HashMap、HashSet) in , With hashCode() after , It is more efficient to determine whether the element is in the corresponding container ( Refer to adding elements into HastSet The process of )!
We also mentioned adding elements to HastSet The process of , If HashSet In contrast , alike hashCode There are multiple objects , It will continue to use equals() To see if it's really the same . in other words hashCode Help us greatly reduce the search cost .
Then why not just provide hashCode() Methods? ?
This is because of the of two objects hashCode Equal values do not mean that two objects are equal .
Then why do two objects have the same hashCode value , And they don't have to be equal ?
because hashCode() The hash algorithm used may just cause multiple objects to return the same hash value . The worse the hash algorithm, the easier it is to collide , But it also has to do with the characteristics of data range distribution ( The so-called hash collision means that different objects get the same hashCode ).
In summary, it is :
- If I have two objects
hashCodeThe values are equal , Then the two objects are not necessarily equal ( Hash collision ). - If I have two objects
hashCodeThe values are equal andequals()Method returnstrue, We think the two objects are equal . - If I have two objects
hashCodeValue inequality , We can directly think that the two objects are not equal .
I believe you have seen me face hashCode() and equals() After the introduction of , The following question is no longer difficult for you .
# Why rewrite equals() Must rewrite hashCode() Method ?
Because two equal objects hashCode Values must be equal . That is to say if equals Method to judge that two objects are equal , The of these two objects hashCode The values should also be equal .
If rewritten equals() There is no rewriting hashCode() Method, it may lead to equals Method determines that two objects are equal ,hashCode The values are not equal .
reflection : rewrite equals() There is no rewriting hashCode() Method words , Use HashMap What could be wrong ?
HashMap The stored value cannot be retrieved , Examples are as follows :
Two are defined Key object , Their id All are 1, It's like they're two identical keys that open the same door . When we went to HashMap Put in k1 when , The first call Key This class of hashCode Method to calculate its hash value , Then put the k1 Put in hash The memory location indicated by the value . I'm still calling theta Object Class hashCode Method ( All classes are Object Subclasses of ), and Object class Of hashCode Method hash Value is k1 The memory address of the object ( The assumption is 1000). Then put the k1 Put in hash The memory location indicated by the value .
If we followed by a call hm.get(k1), So we're going to call it again hashCode Method ( Or return k1 The address of 1000), Then according to the obtained hash value , It can be found very quickly k1.
But here's the code hm.get(k2), When we call Object Class hashCode Method ( because Key No defined in the ) Calculation k2 Of hash When the value of , What you actually get is k2 Memory address of ( The assumption is 2000). because k1 and k2 It's two different objects , So they must not have the same memory address , In other words, their hash It must be different , That's why we can't use it k2 Of hash Value to take k1 Why .
public class WithoutHashCode {
public static void main(String[] args) {
Key k1 = new Key(1);
Key k2 = new Key(1);
HashMap hm = new HashMap();
hm.put(k1, "Key with id is 1");
System.out.println(hm.get(k2));
}
}
rewrite hashCode() There is no rewriting equals() Method words , Use HashMap What could be wrong ?
HashMap There will also be cases where the stored value cannot be retrieved . As above WithoutHashCode Example ,
save k1 when , Is based on it id Of hash value , So let's say that this is 100, hold k1 The object is put into the corresponding position . And take k2 when , I calculated it first hash value ( because k2 Of id It's also 1, This value is also 100), Then look for it in this position .
HashMap Chain address method is used to handle conflicts , in other words , stay 100 No position , It is possible to have multiple objects stored as linked lists . They use hashCode Method hash Values are 100.
Now hm.get(k2) and hm.get(k1) Get the same hash value 100, You need to call Key Object's equals Method to see if they're equal . Because we are Key There is no definition in the object equals Method , The system has to be called Object Class equals Method . because Object Is based on the memory addresses of the two objects , therefore k1 and k2 It's not going to be equal , In the example hm.get(k2) What you get will be null.
summary :
equalsMethod to judge that two objects are equal , The of these two objectshashCodeThe values should also be equal .- Two objects have the same
hashCodevalue , They don't have to be equal ( Hash collision ).
边栏推荐
- 新库上线 | CnOpenData中国观鸟记录数据
- QT learning diary 9 - dialog box
- Loop through JSON object list
- 简单配置PostFix服务器
- [set theory] order relation: summary (partial order relation | partial order set | comparable | strictly less than | covering | hasto | total order relation | quasi order relation | partial order rela
- Introduction to SolidWorks gear design software tool geartrax
- Graduation summary
- Analyse ArrayList 3: suppression d'éléments
- Electronic Science and technology 20th autumn "Microcomputer Principle and application" online assignment 2 [standard answer]
- Online assignment 3 of mobile Internet technology in the 20th autumn of electronic technology [standard answer]
猜你喜欢

Wechat applet for the first time

新库上线 | CnOpenData中国保险机构网点全集数据

QT adjust win screen brightness and sound size

Leetcode 669 pruning binary search tree -- recursive method and iterative method

鸿蒙第三次培训
![[RT thread] NXP rt10xx device driver framework -- Audio construction and use](/img/85/32a83eaa4b7f5b30d4d7c4f4c32791.png)
[RT thread] NXP rt10xx device driver framework -- Audio construction and use
![[RT thread] construction and use of --hwtimer of NXP rt10xx device driver framework](/img/df/a7719bcb00ff66e21f3a391ab94573.png)
[RT thread] construction and use of --hwtimer of NXP rt10xx device driver framework

UE4 official charging resources, with a total price of several thousand
![[combinatorics] recursive equation (summary of the solution process of recursive equation | homogeneous | double root | non-homogeneous | characteristic root is 1 | exponential form | the bottom is th](/img/f1/c96c4a6d34e1ae971f492f4aed5a93.jpg)
[combinatorics] recursive equation (summary of the solution process of recursive equation | homogeneous | double root | non-homogeneous | characteristic root is 1 | exponential form | the bottom is th

【RT-Thread】nxp rt10xx 设备驱动框架之--Pin搭建和使用
随机推荐
[combinatorics] recursive equation (example of solving recursive equation without multiple roots | complete process of solving recursive equation without multiple roots)
AcWing 3438. 数制转换
University of Electronic Science and technology, accounting computerization, spring 20 final exam [standard answer]
When absolutely positioned, the element is horizontally and vertically centered
Web-ui automated testing - the most complete element positioning method
[error reporting] omp: error 15: initializing libiomp5md dll, but found libiomp5md. dll already initialized.
Leetcode 108 converts an ordered array into a binary search tree -- recursive method
免费数据 | 新库上线 | CnOpenData中国保险中介机构网点全集数据
【RT-Thread】nxp rt10xx 设备驱动框架之--hwtimer搭建和使用
Where is the database account used when running SQL tasks in data warehouse tasks configured
[combinatorics] recursive equation (four cases where the non-homogeneous part of a linear non-homogeneous recursive equation with constant coefficients is the general solution of the combination of po
One brush 149 force deduction hot question-10 regular expression matching (H)
Life is still confused? Maybe these subscription numbers have the answers you need!
Stm32h7 Hal library SPI DMA transmission has been in busy solution
Leetcode Valentine's Day Special - looking for a single dog
Internet Hospital his Management Platform source, online Inquiry, appointment Registration Smart Hospital Small program source
link preload prefetch
网络硬盘NFS的安装与配置
基于主机的入侵系统IDS
September, 19, "cam principle and application" online assignment [Full Score answer]