1 == 对于基本数据类型,根据两端的值来判断是否相等,即使两端的数据类型不同,也可以返回true。引用数据类型,比较引用变量类型的地址是否相等
2 equals()是比较引用类型变量是否相等,也是比较地址值
3 ctrl+shift+t 查看源码 ctrl+/ 注释
package lianxi2; public class TestEquals { public static void main(String []args){ Department d1 = new Department(); Department d2 = new Department(); System.out.println(d1 == d2); //false System.out.println(d1.equals(d2)); //Object的equals方法 false String s1 = new String("tt"); String s2 = new String("tt"); System.out.println(s1 == s2); //false System.out.println(s1.equals(s2)); //String类重写equals方法 true } }
package lianxi3; public class TestMyDate { /** * @param args */ public static void main(String[] args) { MyDate md1 = new MyDate(5,27,2014); MyDate md2 = new MyDate(5,27,2014); if(md1 == md2){ // md1!=md2 System.out.println("md1==md2"); } else{ System.out.println("md1!=md2"); } if(md1.equals(md2)){ //true System.out.println("true"); } else{ System.out.println("false"); } } } class MyDate{ private int month; private int day; private int year; public MyDate(int month, int day, int year) { super(); this.month = month; this.day = day; this.year = year; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public int getDay() { return day; } public void setDay(int day) { this.day = day; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } // //手动创建equals // public boolean equals(Object obj){//体现多态性 // if(this==obj){ // return true; // } // else if(obj instanceof MyDate){ // MyDate m = (MyDate)obj; // return this.day==m.day // && this.month == m.month // && this.year == m.year; // } // return false; // } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MyDate other = (MyDate) obj; if (day != other.day) return false; if (month != other.month) return false; if (year != other.year) return false; return true; } }