CharSequence vs. String in Java – Java中的CharSequence与String

最后修改: 2017年 8月 27日

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

1. Introduction

1.介绍

Simply put, CharSequence and String are two different fundamental concepts in Java.

简单地说,CharSequenceString是Java中两个不同的基本概念。

In this quick article, we’re going to have a look at the differences between these types and when to use each one.

在这篇简短的文章中,我们将看看这些类型之间的区别以及何时使用每一种类型。

2. CharSequence

2.CharSequence

CharSequence is an interface that represents a sequence of characters. Mutability is not enforced by this interface. Therefore, both mutable and immutable classes implement this interface.

CharSequence是一个表示字符序列的接口。这个接口不强制执行可变性。因此,可变和不可变的类都实现这个接口。

Of course, an interface can’t be instantiated directly; it needs an implementation to instantiate a variable:

当然,一个接口不能直接实例化,它需要一个实现来实例化一个变量。

CharSequence charSequence = "baeldung";

Here, charSequence is instantiated with a String. Instantiating other implementations:

这里,charSequence被实例化为一个String.实例化其他实现。

CharSequence charSequence = new StringBuffer("baeldung");
CharSequence charSequence = new StringBuilder("baeldung");

3. String

3.字符串

String is a sequence of characters in Java. It is an immutable class and one of the most frequently used types in Java. This class implements the CharSequence, Serializable, and Comparable<String> interfaces.

String是Java中的一个字符序列。它是一个不可变的类,也是Java中最经常使用的类型之一。该类实现了CharSequenceSerializableComparable<String>接口。

Below both instantiations create Strings with the same content. However, they are not equal to each other:

下面这两种实例化都创建了内容相同的字符串。然而,它们彼此不相等。

@Test
public void givenUsingString_whenInstantiatingString_thenWrong() {
    CharSequence firstString = "baeldung";
    String secondString = "baeldung";

    assertNotEquals(firstString, secondString);
}

4. CharSequence vs. String

4.CharSequenceString

Let’s compare the differences and commonalities of CharSequence and String. They both reside in the same package named java.lang., but the former is an interface and latter is a concrete class. Moreover, the String class is immutable.

让我们比较一下CharSequenceString的区别和共同点。它们都位于同一个名为java.lang.的包中,但前者是一个接口,后者是一个具体的类。此外,String类是不可变的。

In the following example, each sum operation creates another instance, increases the amount of data stored and returns the most recently created String:

在下面的例子中,每个和操作都会创建另一个实例,增加存储的数据量,并返回最近创建的String:

@Test
public void givenString_whenAppended_thenUnmodified() {
    String test = "a";
    int firstAddressOfTest = System.identityHashCode(test);
    test += "b";
    int secondAddressOfTest = System.identityHashCode(test);

    assertNotEquals(firstAddressOfTest, secondAddressOfTest);
}

On the other hand, StringBuilder updates the already created String to hold the new value:

另一方面,StringBuilder更新已经创建的String以容纳新值。

@Test
public void givenStringBuilder_whenAppended_thenModified() {
    StringBuilder test = new StringBuilder();
    test.append("a");
    int firstAddressOfTest = System.identityHashCode(test);
    test.append("b");
    int secondAddressOfTest = System.identityHashCode(test);        
    
    assertEquals(firstAddressOfTest, secondAddressOfTest);
}

Another difference is that the interface does not imply a built-in comparison strategy, whereas the String class implements the Comparable<String> interface.

另一个区别是,该接口并不意味着内置的比较策略,而String类实现了Comparable<String>接口。

To compare two CharSequences, we can cast them to Strings then subsequently compare them:

要比较两个CharSequences,我们可以把它们投给Strings,然后再进行比较。

@Test
public void givenIdenticalCharSequences_whenCastToString_thenEqual() {
    CharSequence charSeq1 = "baeldung_1";
    CharSequence charSeq2 = "baeldung_2";
 
    assertTrue(charSeq1.toString().compareTo(charSeq2.toString()) > 0);
}

5. Conclusion

5.结论

We usually use String in the places where we’re not sure what to use for char sequences. However, in some cases, StringBuilder and StringBuffer can be more appropriate.

我们通常在不确定使用char序列的地方使用String。然而,在某些情况下,StringBuilderStringBuffer可能更合适。

You can find more information in JavaDocs about CharSequence and String.

你可以在JavaDocs中找到更多关于CharSequenceString的信息。

And, as always, the implementation of all these examples and code snippets can be found over on Github.

而且,像往常一样,所有这些例子和代码片断的实现都可以在Github上找到over