重写equals

来源:互联网 发布:java web报表插件 编辑:程序博客网 时间:2024/05/05 05:11

</pre><span style="font-size:18px;">1、equals方法和==</span><p></p><p><span style="font-size:18px;"><span style="white-space:pre"></span>对于基础类型而言,“==”比较的是基础类型的值。对于对象而言,“==”比较的是引用,即对象的内存地址</span></p><p><span style="font-size:18px;"><span style="white-space:pre"></span>equals()方法在Object基类中,其内部使用“==”实现的</span></p><pre name="code" class="java"><span style="font-size:18px;"><strong>public boolean equals(Object obj)     return this == obj;}</strong></span>

如果希望不同内存但内容相同烦人两个对象equals时返回true,则我们需要重写Object提供的equals方法

<strong>/*测试重写equals*/<span style="font-size:18px;">class Person{private String name;private String idStr;public Person(){}public Person(String name, String idStr){this.name = name;this.idStr = idStr;}public String getIdStr(){return this.idStr;}public String getName(){return this.name;}public boolean equals(Object obj){if (this == obj){return true;}if (obj != null && obj.getClass() == Person.class){Person personobj = (Person)obj;if (this.getIdStr() == personobj.getIdStr() && this.getName() == personobj.getName()){return true;}}return false;}}public class TestEquals{public static void main(String[] args){Person p1 = new Person("孙悟空", "111");Person p2 = new Person("孙悟空", "111");Person p3 = new Person("孙悟空", "222");System.out.println(p1.equals(p2));}}</span></strong>




<strong><em>public boolean equals(Object obj){if (this == obj){return true;}if (obj != null && obj.getClass() == Person.class){Person personobj = (Person)obj;if (this.getIdStr() == personobj.getIdStr() && this.getName() == personobj.getName()){return true;}}return false;}</em></strong>
</pre><pre name="code" class="java" style="font-size: 18px;">
什么时候需要重写equals
第一种情况:如果类中提供的equals方法无法满足要求
第二种方法:对于采用Hash算法的集合(HashMap, HashSet, Hashtable)集合中对象必须重写hashcode方法,
同时也重写equals方法
</pre><pre name="code" class="java" style="font-size: 18px;">3、为什么不用instaanceOf运算
重写equals()要求通常两个对象时同一个类的实例,因此使用instaanceof运算符不太合适

0 0
原创粉丝点击