Object中的equal()方法详细与"=="

来源:互联网 发布:ubuntu可以干什么 编辑:程序博客网 时间:2024/05/17 04:45
之前一直有点模糊的概念 equal()与==方法的区别!
package com.yangfan.equal;public class Testequal {public static void main(String args[]) {Cat cat1 = new Cat(1, 2, 3);Cat cat2 = new Cat(1, 2, 3);System.out.println(cat2 == cat1);//本质上比较是比较内堆内存的指向引用是否相同!永远是falseSystem.out.println(cat2.equals(cat1));//在没有重写equal()方法之前:false,本质上也是调用了==来比较!                                       //重写equal()后是:true;System.out.println("----------------");String s1 = new String("hello");String s2 = new String("hello");System.out.println(s2 == s1);//这个是指引用结果是:永远是falseSystem.out.println(s2.equals(s1));//String 重写了equal()方法:true;默认重写Date类s}}class Cat {private int color, height, weight;public Cat() {}public Cat(int color, int height, int weight) {super();this.color = color;this.height = height;this.weight = weight;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + color;result = prime * result + height;result = prime * result + weight;return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;final Cat other = (Cat) obj;if (color != other.color)return false;if (height != other.height)return false;if (weight != other.weight)return false;return true;}}


 

 

 

原创粉丝点击