什么是比较StringBuilder对象的有效方法 [英] What is an efficient way to compare StringBuilder objects

查看:122
本文介绍了什么是比较StringBuilder对象的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个StringBuilder对象,我需要在Java中对它们进行比较。
我知道我能做的一种方式是

Well I have two StringBuilder objects, I need to compare them in Java. One way I know I can do is

sb1.toString().equals(sb2.toString());

但这意味着我正在创建两个String对象,有没有更好的方法来比较StringBuilder对象。可能你不需要创建其他对象的东西?

but that means I am creating two String objects, is there any better way to compare StringBuilder objects. Probably something where you do not need to create additional objects?

推荐答案

正如你显然已经知道的那样, StringBuilder java.lang.Object 继承 equals(),并因此 StringBuilder.equals()仅在传递与参数相同的对象时才返回true。它比较两个 StringBuilder 的内容!

As you apparently already know, StringBuilder inherits equals() from java.lang.Object, and as such StringBuilder.equals() returns true only when passed the same object as an argument. It does not compare the contents of two StringBuilders!

如果看一下来源,您将得出结论,最有效的比较(不涉及创建任何新对象)将比较 .length()返回值,然后如果它们是相同的,比较每个字符的 charAt(i)的返回值。

If you look at the source, you'll conclude that the most efficient comparison (that didn't involve creating any new objects) would be to compare .length() return values, and then if they're the same, compare the return values of charAt(i) for each character.

这篇关于什么是比较StringBuilder对象的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆