equals和==小测试
程序员文章站
2022-04-19 23:11:32
...
package testSingle;
import org.junit.Test;
public class TestEqualSingle
{
@Test
public void testSingle()
{
Person p = Person.getInstanse();
Person p1 = Person.getInstanse();
System.out.println(p1 == p);// true
}
/**总结:单例模式产生的对象是同一个对象,==意味着引用的对象是同一个,
* 不管改引用对象是在堆里还是栈里 .*/
@Test
public void testEqules()
{
Person p = Person.getInstanse();
Student s = new Student();
s.setName("张三");
System.out.println(s.equals(p));// true
}
/**
* 总结:然后是equals方法相等,它不管是什么类的对象,只管
* 是否符合能够让equals相等,当你没重写hashcode方法时,不会相等,
* 因为Object写的 hashcode是随机的,equals相等的前提条件是hashcode相同
*/
}
class Student
{
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
@Override
public boolean equals(Object obj)
{
if (obj instanceof Student)
{
Student s = (Student)obj;
if (s.getName() != null)
{
return s.getName().equals(this.name);
}
}
if (obj instanceof Person)
{
Person p = (Person)obj;
if (p.getName() != null)
{
return p.getName().equals(this.name);
}
}
return false;
}
@Override
public int hashCode()
{
return this.name.hashCode();
}
}
class Person
{
private String name;
private static final Person per = new Person();
/** 获取单例 */
public static Person getInstanse()
{
return per;
}
private Person()
{
super();
name = "张三";
}
@Override
public int hashCode()
{
return this.name.hashCode();
}
@Override
public boolean equals(Object obj)
{
if (obj instanceof Student)
{
Student s = (Student)obj;
if (s.getName() != null)
{
return s.getName().equals(this.name);
}
}
if (obj instanceof Person)
{
Person p = (Person)obj;
if (p.getName() != null)
{
return p.getName().equals(this.name);
}
}
return false;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}