java equals函数

来源:互联网 发布:浙江c语言二级考试时间 编辑:程序博客网 时间:2024/05/18 12:38

java中所有类都是Object的子类,Object中实现了equals方法,使用时一般要对其进行重载。

不进行重载时

public class JavaTest{public static void main(String[] args){boolean result;Student stu1=new Student("cjc",24);Student stu2=new Student("cjc",24);result=stu1.equals(stu2);if(result){System.out.println("是同一个人!");}else{System.out.println("不是同一个人!");}}}class Student extends Object{private String name;private int age;Student(String str,int num){name=str;age=num;}}


进行重载后

public class JavaTest{public static void main(String[] args){boolean result;Student stu1=new Student("cjc",24);Student stu2=new Student("cjc",24);result=stu1.equals(stu2);if(result){System.out.println("是同一个人!");}else{System.out.println("不是同一个人!");}}}class Student extends Object{private String name;private int age;Student(String str,int num){name=str;age=num;}public boolean equals(Object o){boolean result=false;if(o instanceof Student){Student stu=(Student)o;if(stu.name.equals(this.name) && this.age==stu.age){result=true;}}return result;}}

需要注意的是String类已经对equals进行了重载,所以程序中stu.name.equals(this.name)才可以这样使用


0 0
原创粉丝点击