package MavenWeb.MavenWeb;
import java.util.HashMap;
import java.util.Map;
public class StringEquality {
public static void main(String[] args) {
Person p1 = new Person("Naveen", 22, 1000);
Person p2 = new Person("Naveen", 21, 2000);
Person p3 = new Person("Naveen", 23, 3000);
if(p1.equals(p2)){
System.out.println("P1 and p2 :" + p1.equals(p2));
} else{
System.out.println("P1 and p2 :" + p1.equals(p2));
}
if(p1.equals(p3)){
System.out.println("P1 and p3 :" + p1.equals(p3));
}
Map<Person, Object> map = new HashMap<Person, Object>();
map.put(p1, p1);
map.put(p2, p2);
System.out.println(map.get(new Person("Naveen", 21, 2000)));
}
}
Run Code Online (Sandbox Code Playgroud)
...
class Person{
public Person(String name, int id, float salary){
this.name = name;
this.id = id;
this.salary = salary;
}
public Float getSalary() {
return salary;
}
public void setSalary(Float salary) {
this.salary = salary;
}
String name;
Float salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
int id;
@Override
public boolean equals(Object obj) {
if(obj == null){
return false;
}
if(this == obj){
return true;
}
if(obj instanceof Person){
Person person = (Person)obj;
if((person.getName().equals(name)) && person.getId() == id
&& person.getSalary() == salary){
return true;
}
}
return false;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = 31 * hashCode + name.hashCode();
hashCode = 31 * hashCode + id;
hashCode = 31 * hashCode + salary.intValue();
return hashCode;
}
@Override
public String toString() {
return "Name :" + name + ", id : " + id;
}
}
Run Code Online (Sandbox Code Playgroud)
我写了以下程序.有关哈希码实现的一点点困惑,
你从地图上得到了null,因为薪水存储为Float(而不是float),而你正在比较Float实例==而不是比较它们equals().
因此equals(),Person 的方法检查Float两个Person实例中的实例完全相同,而不是检查它们的工资值是否相等.您应该使用float(或更好double:),除非工资可以为空(您还应考虑使用BigDecimal来处理确切的金额).但在这种情况下,您必须检查空值Person.equals()并用于equals()比较工资.在Java 7或更高版本中,最简单的方法是使用Objects.equals()可空对象进行比较:
@Override
public boolean equals(Object obj) {
if(obj == null){
return false;
}
if(this == obj){
return true;
}
if(obj instanceof Person){
Person person = (Person)obj;
return Objects.equals(name, person.name)
&& id == person.id
&& Objects.equals(salary, person.salary);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(name, id, salary);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1233 次 |
| 最近记录: |