Java的equals()和==的区别

Java中==就是用来比较值是否相等,equals()是父类Object提供的一个方法equals(Object obj),在Java API文档中提到:

  • The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true). 

即如果不在自己的类重新实现的话作用等于==。

 

Java的数据类型分为引用型和基本类型

基本类型有4类8种:

     浮点型:float(4 byte), double(8 byte)

  整型:byte(1 byte), short(2 byte), int(4 byte) , long(8 byte)

  字符型: char(2 byte)

  布尔型: boolean(JVM规范没有明确规定其所占的空间大小,仅规定其只能够取字面值"true"和"false")

在Java中存放的就是具体值,(其值存放在data segment),用==比较的就是data segment中的值

int a = 1; int b = 1;

a==b; 返回true //基本类型不能用equals()比较

引用类型有3中:

      自定义类,数组,接口

当声明引用类型时,如 Animal a = new Animal("cat");      Animal b = new Animal("cat");

其中a,b存在栈上,new出的两个对象存在堆上, 此时a==b为false, 因为栈上的a,b存的是new出对象的地址,通过此地址可以找到对象,a,b的值是不同的,同样如果Animal类没有重写equals()方法,返回值和==一样为false

特殊的是String类自动为我们重写了equals()方法,Java API中写到

  • public boolean equals(Object anObject)
    Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

它比较的是String的具体内容,即字符串的值

String a = new String("hello");

String b = new String("hello");

a==b;//false

a.equals(b);//true

posted @ 2017-02-22 22:02  阿童木木  阅读(137)  评论(0编辑  收藏  举报