1. 操作符”==”用来比较两个操作元是否相等,这两个操作元既可以是基本类型,也可以是引用类型。
例如:int a1=1,a2=3;
boolean b1=a1==a2; //”==”的操作元为基本类型,b1值为false
String str1=”Hello”,str2=”World”;
boolean b2=str1==str2; //”==”的操作元为引用类型,b2的值为false
2. 当操作符“==”两边都是引用类型变量时,这两个引用变量必须都引用同一个对象,结果才为true,否则为false.
如:class IntegerMethod {
void method() {
Integer int1 = new Integer();
Integer int2 = new Integer();
Integer int3 = int1;
System.out.println("int1==int2 is " + (int1 == int2));
System.out.println("int1==int3 is " + (int1 == int3));
System.out.println("int2==int3 is " + (int2 == int3));
}
}
public class Integer {
public static void main(String[] args) {
IntegerMethod im = new IntegerMethod();
im.method();
}
}
结果为:int1==int2 is false
int1==int3 is true
int2==int3 is false
3. 当“==”用于比较引用类型变量时,“==”两边的变量被显式声明的类型必须是同种类型或有继承关系。
class Creature {
Creature() {
}
}
class Animal extends Creature {
Animal() {
}
}
class Dog extends Animal {
Dog() {
}
}
class Cat extends Animal {
Cat() {
}
}
public class IntegerTest {
public static void main(String[] args) {
Dog dog = new Dog();
Creature creature = dog;
Animal animal = new Cat();
System.out.println(dog == animal);
System.out.println(dog == creature);
}
}
结果为:false
true
4.Object类的equals()方法比较规则为:当参数obj引用的对象与当前对象为同一个对象时,就返回true,否则返回false.两者的区别是“==”比较的是变量的值(也即为内存地址),而equals()比较的是变量的内容。
class ConInteger {
Integer int1 = new Integer(1);
Integer int2 = new Integer(1);
String str1 = new String("Hello");
String str2 = new String("Hello");
void print() {
System.out.println(int1 == int2);
System.out.println(int1.equals(int2));
System.out.println(str1 == str2);
System.out.println(str1.equals(str2));
}
}
public class TestInteger {
public static void main(String[] args) {
new ConInteger().print();
}
}
结果为:false
true
false
true
5.只要两个对象都是同一个类的对象,并且它们变量属性相同,则结果为true,否则为false.
class TestInteger{
private String name;
TestInteger(String name){
this.name=name;
}
boolean equal(Object o){
if(this==o){
return true;
}
if(!(o instanceof TestInteger)){
return false;
}
final TestInteger other=(TestInteger)o;
if(this.name.equals(other.name)){
return true;
}
else{
return false;
}
}
}
public class TestIntegerOne {
public static void main(String[] args) {
TestInteger person1=new TestInteger("Tom");
TestInteger person2=new TestInteger("Tom");
System.out.println(person1==person2);
System.out.println(person1.equal(person2));
}
}
结果为:false
true