The following are covered:
public class User
{
Private Integer ID;
Private String UserName;
Private String PassWord;
Public Integer getId () {
return ID;
}
public void SetId (Integer id) {
This.id = ID;
}
Public String GetUserName () {
return userName;
}
public void Setusername (String userName) {
This.username = UserName;
}
Public String GetPassword () {
return PassWord;
}
public void SetPassword (String passWord) {
This.password = PassWord;
}
@Override
public boolean equals (Object O)
{
if (this = = O)
return true;
if (o = = NULL | | getclass ()! = O.getclass ())
return false;
User user = (user) O;
if (id! = null?!id.equals (user.id): User.ID! = null)
return false;
if (userName! = null?!username.equals (User.username)
: User.username! = null) {
return false;
}
if (PassWord! = null?!password.equals (User.password): User.password! = null) {
return false;
}
return true;
}
@Override
public int hashcode ()
{
int result = ID! = NULL? Id.hashcode (): 0;
result = * result + (UserName! = null? Username.hashcode (): 0);
result = * result + (PassWord! = null? Password.hashcode (): 0);
return result;
}
}
1. The key convention that does not overwrite hashcode and violates is the second: equal hash code must be equal for the object.
2, rewrite hashcode Choose 31 Reason: 31 is a singular prime, if the multiplier is an even number, and multiplication overflow, the information will be lost, because 2 multiplication is equivalent to the shift operation, and 31 has a good feature, that is, shift and subtraction to replace the multiplication, you can get better performance: 31*i= (i <<5)-I, a modern VM can automatically do this optimization.
3. result = 31*result +c;
The hash code c rules for the int type are computed for each critical field F:
1) Boolean: Calculation (f?1:0);
2) Byte,int,char,short: calculation (int) F;
3) long: calculation (int) (f~ (f>>>32));
4) Float: Calculate float.floattointbits (f);
5) Double: calculate double.doubletolongbits (f);
6) object reference or array: Each element is treated as a separate domain
Overwrite equals () always overwrite hashcode ()