Java面试题 ==和equals的区别

==

运算符

1. 可以使用在 基本数据类型变量 和 引用数据类型变量中;

2. 基本数据类型:

比较两个变量 保存的数据 是否相等。(不一定类型要相同)

int i = 10;
int j = 10;
double d = 10.0;
System.out.println(i == j); // true
System.out.println(i == d); // true,存在自动类型提升

boolean b = true;
System.out.println(i == d); // 不可以比较

char c = 10;
System.out.println(i == c); // true

char c1 = 'A';
char c2 = 65;
System.out.println(c1 == c2); // true

    引用数据类型:

比较两个变量的 地址值 是否相等,即两个引用是否指向同一个对象实体。

Customer cust1 = new Customer("Tom", 21);
Customer cust2 = new Customer("Tom", 21);
System.out.println(cust1 == cust2); // false
String str1 = new String("gengsj");
String str2 = new String("gengsj");
System.out.println(str1 == str2); // false

equals()

1. 方法,而非运算符

2. 只能使用于 引用数据类型

Customer cust1 = new Customer("gengsj", 21);
Customer cust2 = new Customer("gengsj", 21);
System.out.println(cust1.equals(cust2)); // false

String str1 = new String("gengsj");
String str2 = new String("gengsj");
System.out.println(str1.equals(str2)); // true

3. Object类中equals的定义:和 == 作用相同,比较两个对象的地址值是否相同,是否指向同一个实体。

public boolean equals(Object obj) {
        return (this == obj);
}
// Params: obj – the reference object with which to compare.
// Returns: true if this object is the same as the obj argument; false otherwise.

4. 像String、Date、File、包装类等都重写了Object类中的 equals()方法。重写以后,比较的不是两个引用的地址是否相同,而是比较两个对象的“实体内容”是否相同。

例如:String中的equals()方法

public boolean equals(Object anObject) {
    if (this == anObject) { // 引用地址相同的话,一定是一个对象,不用比了
        return true;
    }
    if (anObject instanceof String) { // 判断 对象类型是否相同。不相同返回false
        String anotherString = (String)anObject;
        int n = value.length; // 当前字符串的长度
        if (n == anotherString.value.length) { // 判断字符串的长度是否相同
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) { // 依次遍历两个字符串,如果有不同的,就返回false
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true; // 遍历完,没有出现不同的,返回true
        }
    }
    return false;
}
//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.
//Params: anObject – The object to compare this String against
//Returns:
//true if the given object represents a String equivalent to this string, false otherwise
//把这个string对象和特定的对象比较。如果只要这个对象不是null且是一个字符串对象,这个对象表示
//这个对象相同的字符序列

5. 通常情况下,我们自定义的类如果使用 equals() 的话,也通常是比较两个对象的“实体内容”是否相同。那么,我们就需要对 Object类中的 equals() 方法进行重写。

重写的原则:比较两个对象的“实体内容”是否相同

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值