Compare StringBuilder Objects in Java – 比较 Java 中的 StringBuilder 对象

最后修改: 2023年 11月 7日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In Java, the StringBuilder class allows us to create a mutable object holding a sequence of characters. This makes it easy to update the object without building it from scratch each time, as would be the case with the standard String class. In this tutorial, we’ll look at how to compare two StringBuilder objects both before and after the release of Java 11.

在 Java 中,StringBuilder 类允许我们创建一个容纳字符序列的可变对象。这样就可以轻松更新对象,而无需像标准 String 类那样每次都从头开始构建。在本教程中,我们将了解如何比较 Java 11 发布之前和之后的两个 StringBuilder 对象。

2. Before Java 11

2.Java 11 之前

Before Java 11, there was no built-in comparison method for the StringBuilder. Therefore, we’ll need to write our own. The first obvious check to do is if the two objects being compared are the same length. If not, we can immediately say they don’t match.

在 Java 11 之前,StringBuilder 没有内置比较方法。因此,我们需要编写自己的比较方法。要做的第一个显而易见的检查是比较的两个对象的长度是否相同。如果不一致,我们可以立即判定它们不匹配。

Once we know they are the same length, we can use the fact that StringBuilder implements CharSequence to access the charAt() method and compare each character in turn. Let’s combine those two steps into a single method we can use:

一旦知道它们的长度相同,我们就可以利用 StringBuilder 实现 CharSequence 这一事实来访问 charAt() 方法,并依次比较每个字符。让我们将这两个步骤合并为一个我们可以使用的方法:

boolean compare(StringBuilder one, StringBuilder two) {
    if (one.length() != two.length()){
        return false;
    }
    for (int i = 0; i < one.length(); i++) {
        if (one.charAt(i) != two.charAt(i)) {
            return false;
        }
    }
    return true;
}

We can now use that in a few tests. Let’s see if it confirms two StringBuilders are the same:

现在我们可以在一些测试中使用它。让我们看看它是否能确认两个 StringBuilders 是相同的:

@Test
void whenUsingJavaEight_givenTwoIdenticalStringBuilders_thenCorrectlyMatch() {
    StringBuilder one = new StringBuilder("Hello");
    StringBuilder two = new StringBuilder("Hello");
    boolean result = StringBuilderCompare.compare(one, two);
    assertEquals(true, result);
}

To complete the checks, let’s now see that it can detect two which aren’t the same:

为了完成检查,我们现在来看看它是否能检测出两个不相同的数据:

@Test
public void whenUsingJavaEight_givenTwoDifferentStringBuilders_thenCorrectlyIdentifyDifference() {
    StringBuilder one = new StringBuilder("Hello");
    StringBuilder two = new StringBuilder("World");
    boolean result = StringBuilderCompare.compare(one, two);
    assertEquals(false, result);
}

The examples in the second test are the same length, so we will be using the charAt() comparisons.

第二个测试中的示例长度相同,因此我们将使用 charAt() 比较。

3. After Java 11

3.Java 11 之后

With the release of Java 11 StringBuilder now implements Comparable. This gives us access to the compareTo() method which returns an int. The return value will be zero if there’s a match and not zero in the event of the StringBuilders being different. Let’s see that in action with two StringBuilders with the same value:

Java 11 发布后,StringBuilder 现在实现了 Comparable这使我们能够访问 compareTo() 方法,该方法返回一个 int如果存在匹配,则返回值为 0,如果 StringBuilder 不同,则返回值不为 0。让我们看看两个具有相同值的 StringBuilders 的实际运行情况:

@Test
void whenUsingJavaEleven_givenTwoIdenticalStringBuilders_thenCorrectlyMatch(){
    StringBuilder one = new StringBuilder("Hello");
    StringBuilder two = new StringBuilder("Hello");
    assertEquals(0, one.compareTo(two));
}

Following that let’s try it with two different values:

接下来,让我们用两个不同的值来试试:

@Test
void whenUsingJavaEleven_givenTwoDifferentStringBuilders_thenCorrectlyIdentifyDifference(){
    StringBuilder one = new StringBuilder("Hello");
    StringBuilder two = new StringBuilder("World");
    assertNotSame(0, one.compareTo(two));
}

This is now much easier than before Java 11. The returned integer tells us if the two under comparison are lexicographically different. We’ll be able to tell if the difference was positive or negative as well which may be useful in some applications.

现在这比 Java 11 之前要容易得多。返回的整数会告诉我们被比较的两个数据是否存在词法上的差异。我们还能知道差值是正还是负,这在某些应用中可能很有用。

4. Conclusion

4.结论

In this article, we’ve looked at two ways of comparing StringBuilder objects. We’ve seen that if we are working with a version of Java older than 11, we’ll need to write our own comparison method. However, with Java 11 onwards we are provided with the convenient compareTo() method, which achieves the same result.

在本文中,我们介绍了比较 StringBuilder 对象的两种方法。我们看到,如果我们使用的 Java 版本早于 11,我们就需要编写自己的比较方法。但是,在 Java 11 以后的版本中,我们可以使用方便的 compareTo() 方法来实现相同的结果。

As always, the full code for the examples is available over on GitHub.

与往常一样,这些示例的完整代码可在 GitHub 上获取。