转载:http://blog.csdn.net/bluesky_usc/article/details/51849125
1值比较
即内容相同,我们就认为是相等的。比如:int i=5;int j =5;此时我们说i和j相等,其实指的是i和j的内容相同。
2引用类型比较
但在Java中,除了值类型,另外还有一种引用类型,而不同的对象,其引用值其实并不相等,即在内存中的不同的地 址单元中。比如我们定义了学生类,分别有两个学生对象实例 :
Student stu= new Student(); Student stu1= new Student();
此时我们无论是使用stu==stu1符号,或者stu.equals(stu1)方法,把两个对象进行比较,得到的结果都是不相等的,因为对于引用类型来说,默认是比较两个对象引用的地址,显示,每个对象的引用有自己唯一的地址,所以,是不相等。
有时,我们比较两个对象时,如果他们的内容一样,那么我们就认为这两个对象是相等的,如上面的两个学生对象。这时,我们该怎么办呢?其实,非常简单,只要在类里面重写equals()方法,进行对象里面的内容比较久可以了。如上面,我们只需要在Student类中重写equals()方法即可。
下面,让我们来看看实例吧! 没有重写equals()方法时的比较:
学生类:Student类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Student 2 { 3 int num; 4 String name; 5 Student(int num,String name){ 6 this.num=num; 7 this.name=name; 8 } 9 10 public int hashCode(){ 11 return num*name.hashCode(); 12 } 13 14 public boolean equals(Object obj){ 15 Student s =(Student)obj; 16 return num==s.num && name.equals(s.name); 17 } 18 19 public String toString(){ 20 return num+"name:"+name; 21 } 22 }
测试类Test:
1.package com.bluesky; 2. 3.public class Test { 4. 5. public static void main(String[] args) { 6. 7. int i=5; 8. int j=5; 9. 10. if(i==j) System.out.println("i和j相等!"); 11. else System.out.println("不相等!"); 12. 13. Student s = new Student("BlueSky"); 14. Student s1=new Student("BlueSky"); 15. 16. if(s==s1) System.out.println("s和是s1相等!"); 17. else System.out.println("s和是s1不相等!"); 18. 19. if(s.equals(s1)) System.out.println("s和是s1相等!"); 20. else System.out.println("s和是s1不相等!"); 21. } 22.}
运行结果:
重写equals()方法后再次进行比较:
Student类:
package com.bluesky; 1. 2.public class Student { 3. 4. String name; 5. 6. public Student(){ 7. 8. } 9. 10. public Student(String name){ 11. 12. this.name=name; 13. 14. } 15. 16. 17. public boolean equals(Object obj) { 18. if (this == obj) //传入的对象就是它自己,如s.equals(s);肯定是相等的; 19. return true; 20. if (obj == null) //如果传入的对象是空,肯定不相等 21. return false; 22. if (getClass() != obj.getClass()) //如果不是同一个类型的,如Studnet类和Animal类, 23. //也不用比较了,肯定是不相等的 24. return false; 25. Student other = (Student) obj; 26. if (name == null) { 27. if (other.name != null) 28. return false; 29. } else if (!name.equals(other.name)) //如果name属性相等,则相等 30. return false; 31. return true; 32. } 33. 34. 35.}
测试类Test:
package com.bluesky; 1. 2.public class Test { 3. 4. public static void main(String[] args) { 5. 6. int i=5; 7. int j=5; 8. 9. if(i==j) System.out.println("i和j相等!"); 10. else System.out.println("不相等!"); 11. 12. Student s = new Student("BlueSky"); 13. Student s1=new Student("BlueSky"); 14. 15. if(s==s1) System.out.println("s和是s1相等!"); 16. else System.out.println("s和是s1不相等!"); 17. 18. if(s.equals(s1)) System.out.println("s和是s1相等!"); 19. else System.out.println("s和是s1不相等!"); 20. } 21.}
运行结果:
重写equals()方法后,得到s和s1相等。==对引用类型的只能进行地址比较,故还是不相等的。