VerySource

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 932|回复: 2

请教为什么StringBuffer比较后输出Not Equal

[复制链接]

1

主题

20

帖子

15.00

积分

新手上路

Rank: 1

积分
15.00
发表于 2020-1-20 11:40:01 | 显示全部楼层 |阅读模式
class D
{

    public static void main(String[] args)
    {

        String s1 = new String("hello");

        String s2 = new String("hello");

        if (s1.equals(s2))

            System.out.println("equal");

        else

            System.out.println("not equal");

    }

}

class E
{

    public static void main(String[] args)
    {

        StringBuffer sb1 = new StringBuffer("hello");

        StringBuffer sb2 = new StringBuffer("hello");

        if (sb1.equals(sb2))

            System.out.println("equal");

        else

            System.out.println("not equal");

    }

}

Class D输出equal,这个可以理解
但是Class E 为什么是not equal呢?StringBuffer的机制是怎么样的?
回复

使用道具 举报

0

主题

6

帖子

7.00

积分

新手上路

Rank: 1

积分
7.00
发表于 2020-1-29 16:09:01 | 显示全部楼层
StringBuffer调用的是Object的equals()方法,它比较的是是否指向 同一个对象,和==一样。

for non-null reference values x and y,this method returns true,if and only if x and y refer to the same object
回复

使用道具 举报

1

主题

20

帖子

15.00

积分

新手上路

Rank: 1

积分
15.00
 楼主| 发表于 2020-1-30 11:36:01 | 显示全部楼层
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).

当且仅当x和y引用了同一对象时才返回true,明白了,多谢44964869。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|CopyRight © 2008-2023|verysource.com ( 京ICP备17048824号-1 )

快速回复 返回顶部 返回列表