Java查漏补缺2 - 等于判断

基础的只是大家都很清楚,对于原始类型如int, float,直接用==就可以比较。对于Class类型的,在Java中使用的是reference的比较,因此需要使用的是equals.

Integer a1 = new Integer(1);
Integer a2 = new Integer(1);
System.out.println(a1==a2); //false
System.out.println(a1.equals(a2)); //true

因此在上述代码中,尽管使用的看上去就是int,但是因为实际已经使用了Integer,所以单纯使用==是不能比较的。

对于自己定义的类型,如果直接使用equals来比较,将会同样返回非期望的值。因为新定义的类,一般不会去重写equals的方法,而会直接调用其父类的equals方法,将也是直接比较reference。如果我们需要比较自定义的类型的时候,只需要重写equals方法就可以了。

class MyClass{
        private int count;
        public MyClass(int a){
            this.count=a;
        }

    @Override
    public boolean equals(Object obj) {
        MyClass newmc = (MyClass)obj;
        return this.count==newmc.count ? true : false;
    }

MyClass m1 = new MyClass(1);
MyClass m2 = new MyClass(1);
System.out.println(m1==m2);
System.out.println(m1.equals(m2));

This entry was posted on Sunday, June 21st, 2009 at 12:19 pm and is filed under J2SE . You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Comments are closed.

  • English Version

    • Cannot read Chinese? Please take a look at my English site, hope you can find more you need there!
  • 感谢支持

  • twitter

    facebook

    linkedin

  • Categories