Equals方法(Java)

来源:互联网 发布:网络手机电视直播 编辑:程序博客网 时间:2024/06/06 03:12
3-1 Equals方法1、不用==来比较是否相等,要用Equals方法来比较2、 Equals方法默认属于Object类并且不是final类型,所以任何类都可以继承并且覆盖此方法3、对象之间不能再用“==”进行比较,这样比较的是对象的内存地址,而不是对象的具体属性。(new之后的对象)4、覆盖后的equals方法比较不是内存地址,而是根据需求来决定返回true或者false的规则。程序示例:public class Hello {    /**     * @param args the command line arguments     */    public static void main(String[] args)     {             B  b1=new B(20);             B  b2=new B(20);          // System.out.println(b1==b2);//违反规则始终返回false           //若没有重写equals方法执行下面语句,无论怎样都返回false。equals参数默认都为object             System.out.println(b1.equals(b2));    }   public static class B    {         private int i;//属性i         public  B(int i) //B类有参构造方法        {            this.i =i;        }     public boolean equals(B b2) //重写equals的方法        {             if (this.i==b2.i)                 return true;             else                 return false;        }        }3-2 Equals方法21、equals方法一般情况下都需要覆盖成自己想要的方法(根据自己的的需求定义两对象相等的条件)。2、配合多态可实现强大的比较功能,可比较类中的任何数据。程序示例:import java.util.*;public class Hello {    /**     * @param args the command line arguments     */    public static void main(String[] args)     {                C c1=new C(10);             C c2=new C(10);               System.out.println(c1.equals(c2));    }   public static class B    {         private int i;//属性i         public  B(int i) //B类有参构造方法        {            this.i =i;        }     public boolean equals(B b2) //重写equals的方法        {             if (this.i==b2.i)                 return true;             else                 return false;        }   }   public static class C extends B    {           private int j;            public C(int j) {                super(j); //优先调用子类                this.j = j;  //不在利用继承过来的方法i的引用            }            //若不重写方法,则调用父类的equals方法 B b2=new C(),子类调用函数是采用引用的方式             public boolean equals(B b2) //重写equals的方法,B类的引用        {                 C  x=(C)b2;//强制转化类型转化为C类的对象,因为当前j为c类对象             if (this.j==x.j)                 return true;             else                 return false;        }               }        }

原创粉丝点击