如何在Java内部表示字符串?

Wil*_*ill 6 java string

我知道C字符串abc内部会abc\0在C中,是否与Java相同?

duf*_*ymo 11

不,它在Java中不一样.没有空终止符.Java字符串是对象,而不是指向字符数组.它保持长度以及Unicode字符,因此不需要查找空终止符.

您不必在此处询问:查看JDK附带的src.zip中String.java的源代码.这是它的开始:

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence
{
    /** The value is used for character storage. */
    private final char value[];

    /** The offset is the first index of the storage that is used. */
    private final int offset;

    /** The count is the number of characters in the String. */
    private final int count;

    /** Cache the hash code for the string */
    private int hash; // Default to 0

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -6849794470754667710L;
}
Run Code Online (Sandbox Code Playgroud)


ale*_*lex 8

不,C字符串是一个字符数组,因此没有与它们相关的长度.这个决定的副作用是要确定一个字符串的长度,必须通过它来迭代才能找到它\0,这对于携带长度来说效率并不高.

Java字符串为其字符设置了char数组,并带有偏移长度和字符串长度.这意味着确定字符串的长度是相当有效的.

来源.

  • @buruzaemon:你知道甚至角色也应该坐在某个地方,对吗? (4认同)
  • 呃......"椅子"? (2认同)