标签:des c style class blog code
1.equals函数在哪
2.equals函数的作用
3.equals函数方法的复写
1.equals函数在哪
包含在Object类, 而Object是所有类的父类, 因此所有类都有equals函数
2.equals函数的作用
首先讲"=="的概念, 再讲equals, 不能混淆这两个
编辑器使用sublime_Text代替Notepad, 界面确实很好看
1 class User{ 2 String name; 3 int age; 4 }
1 class Test{ 2 public static void main(String args []){ 3 User u1 = new User(); 4 User u2 = new User(); 5 User u3 = u1; 6 7 boolean b1 = u1 == u2; 8 boolean b2 = u1 == u3; 9 System.out.println(b1); 10 System.out.println(b2); 11 } 12 }
再来看看equals函数, equals比较两个对象内容是否相等
1 class User{ 2 String name; 3 int age; 4 5 public boolean equals(Object obj){ //判断是否指向堆内存同一个对象 6 if(this == obj){ 7 return true; 8 } 9 10 boolean b = obj instanceof User; 11 if(b){ 12 User u = (User)obj; 13 if(this.age == u.age && this.name.equals(u.name)){ 14 return true; 15 } 16 else{ 17 return false; 18 } 19 } 20 else{ 21 return false; 22 } 23 } 24 }
1 class Test{ 2 public static void main(String args []){ 3 User u1 = new User(); 4 User u2 = new User(); 5 User u3 = new User(); 6 7 u1.name = "zhangsan"; 8 u1.age = 12; 9 10 u2.name = "lisi"; 11 u2.age = 12; 12 13 u3.name = "zhangsan"; 14 u3.age = 12; 15 16 System.out.println(u1.equals(u2)); 17 System.out.println(u1.equals(u3)); 18 } 19 }
标签:des c style class blog code
原文地址:http://www.cnblogs.com/iMirror/p/3760529.html