==和equals

== 对比的是栈中的值,基本数据类型是变量值,引用类型是堆中内存对象的值。

equals:object中默认也是采用== 进行比较,通常会重写

String已经重写了equals方法,如下实际上是比较两个字符串中每一个字符的内容。

    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            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) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

例子

public class Main {
    public static void main(String[] args) {
        String s1 = "111";
        String s2 = new String("111");
        String s3 = s2;
        System.out.println(s1 == s2);//false
        System.out.println(s1 == s3);//false
        System.out.println(s2 == s3);//true
        System.out.println(s1.equals(s2));//true
        System.out.println(s1.equals(s3));//true
        System.out.println(s2.equals(s3));//true
    }
}

字符串s1这种方式来定义字符串,实际上是在堆中的常量池里定义的,111是在常量池里的。
通过new的是在存的内存地址。
通过=号复制,赋值的就是引用地址。
equals()方法String已经重写了,所以无论怎么比较都是true。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值