Java 字符串和字符数组的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18288799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:05:23  来源:igfitidea点击:

Difference between a string and an array of characters

java

提问by Shivaji More

How are these declarations different from each other?

这些声明彼此有何不同?

String s="MY PROFESSION";
char c[]="MY PROFESSION";

What about the memory allocation in each case?

每种情况下的内存分配情况如何?

采纳答案by Prashant Bhate

To correct compilation error replace with one of the below char[]statement

要更正编译错误,请替换为以下char[]语句之一

String s = "MY PROFESSION";
char c1[] = "MY PROFESSION".toCharArray();
char c2[] = { 'M', 'Y', ' ', 'P', 'R', 'O', 'F', 'E', 'S', 'S', 'I', 'O', 'N' };
StringBuilder sb = new StringBuilder("MY PROFESSION");
StringBuffer sbu = new StringBuffer("MY PROFESSION");

Following section compares above statement with each other

以下部分将上述陈述相互比较

String Constant

字符串常量

String s="MY PROFESSION";

Character Array

字符数组

 char c1[]="MY PROFESSION".toCharArray();
 char c2[]={'M', 'Y', ' ', 'P', 'R', 'O', 'F', 'E', 'S', 'S', 'I', 'O', 'N'};
  • c1holds copy of String's underlying array (via System.arraycopy) and stored in heap space
  • c2is built on the fly in the stack frame by loading individual character constants
  • c1& c2are mutable i.e content of Arraycan be modified. c2[0]='B'
  • Size/Length of Array is fixed (not possible to append)
  • c1保存 String 底层数组的副本(via System.arraycopy)并存储在堆空间中
  • c2通过加载单个字符常量在堆栈帧中动态构建
  • c1&c2是可变的,即Array可以修改的内容。c2[0]='B'
  • 数组的大小/长度是固定的(不能追加)

StringBuilder / StringBuffer

字符串构建器/字符串缓冲区

StringBuilder sb = new StringBuilder("MY PROFESSION");
StringBuffer sbu = new StringBuffer("MY PROFESSION");
  • Both sband sbuare mutable. sb.replace(0, 1, 'B');
  • Both sband sbuare stored in heap
  • Size/Length can be modified. sb.append( '!');
  • StringBuffer's methods are synchronised while StringBuilder's methods are not
  • 这两个sbsbu是可变的。sb.replace(0, 1, 'B');
  • 双方sbsbu存储在堆
  • 尺寸/长度可以修改。 sb.append( '!');
  • StringBuffer的方法是同步的,而StringBuilder的方法不是

回答by Rahul Tripathi

charis a primitive type. Stringis a class in which actual data is stored internally as a character array

char是原始类型。String是一个类,其中实际数据在内部存储为字符数组

char c[]="MY PROFESSION";

will give compilation error.

会给出编译错误。

Character array is the contiguous storage in memory where characters are stored sequentially.

字符数组是内存中的连续存储,字符按顺序存储。

Check out this Threadfor more details.

查看此主题以了解更多详细信息。

回答by Suresh Atta

If you see the docs,

如果你看到文档

     String str = "abc";

is equivalent to:

     char data[] = {'a', 'b', 'c'};  //  not 'abc'
     String str = new String(data);

More over String literals are very special in java

更多关于String 文字在 Java 中非常特殊

Stringis backed by a characterarray internally.

Stringcharacter内部数组支持。

回答by JB Nizet

The first one compiles. The second one doesn't.

第一个编译。第二个没有。

A char[]is just that: an array of primitive numbers of type char. All it provides is a lengthattribute, and a way to get and set a char at a given index.

Achar[]就是这样:一个 char 类型的原始数字数组。它提供的只是一个length属性,以及一种在给定索引处获取和设置字符的方法。

A String is an object, of type java.lang.String, which has a whole lot of useful methods for manipulating Strings. Internally, it uses a char array.

String 是一个java.lang.String类型的对象,它有很多有用的方法来操作字符串。在内部,它使用一个字符数组。

Another important feature of String is that it's immutable. You can pass a String to any method and be sure that this method won't change the contents of the String. That is not the case with a char array.

String 的另一个重要特性是它是不可变的。您可以将字符串传递给任何方法,并确保此方法不会更改字符串的内容。字符数组不是这种情况。

Regarding memory, a String consumes some more bytes, but that's generally not what should guide your design decisions: generally, using a char array is not what you should do.

关于内存, String 消耗更多字节,但这通常不是指导您设计决策的内容:通常,使用 char 数组不是您应该做的。

回答by arshajii

How this declaration differentiate from each other?

这个声明如何区分?

Your first line produces a Stringinstance. Your second line is simply invalid; perhaps you meant:

你的第一行产生一个String实例。你的第二行根本无效;也许你的意思是:

char[] c = {'M', 'Y', ' ', 'P', 'R', 'O', 'F', 'E', 'S', 'S', 'I', 'O', 'N'};

which creates char[]filled with those characters.

这创造了char[]充满那些字符。

what about its memory allocation?

它的内存分配怎么样?

Storing a string as a Stringis slightly different memory-wise than storing it as a char[]. There are similarities though: both are objects, and have the usual object overhead.

将字符串String存储为 a 与将其存储为 a 在内存方面略有不同char[]。但是有相似之处:两者都是对象,并且具有通常的对象开销。

However, a Stringholds a char[]internally, so naturally a Stringconsumes more memory. Furthermore, Stringhas 3 intfields (offset, countand hash) whereas char[]has the single intfield length.

但是, aStringchar[]内部持有 a ,因此 a 自然String会消耗更多内存。此外,String具有 3 个int字段 ( offset,counthash) 而char[]具有单个int字段length

For example, storing "MY PROFESSION"as a String:

例如,存储"MY PROFESSION"String

  • 3 intfields: 12bytes
  • char[]field: 8bytes
    • intfield: 4bytes
    • object overhead: 8bytes
    • 13 characters: 26bytes
  • object overhead: 8bytes
  • 3 个int字段:12个字节
  • char[]字段:8字节
    • int字段:4个字节
    • 对象开销:8字节
    • 13 个字符:26个字节
  • 对象开销:8字节

This comes out to about 66bytes. I say "about" because some of this is dependent on the VM. The corresponding char[]of length 10 only consumes 38bytes, as you can see. The memory difference here is quite negligible so you shouldn't worry about it (and just use a String!). It becomes even more insignificant the longer the string you are trying to store becomes.

这大约有66个字节。我说“大约”是因为其中一些取决于 VM。如你所见char[],长度为10的对应只消耗38个字节。这里的内存差异可以忽略不计,因此您不必担心(只需使用String!)。您尝试存储的字符串越长,它就变得越微不足道。

回答by Edwin Buck

An array of characters is mutable, in other words, you can replace a character in an array of characters by overwriting the memory location for that character.

字符数组是可变的,换句话说,您可以通过覆盖该字符的内存位置来替换字符数组中的字符。

A String is not mutable, in other words, to "replace" a character in a String, you must build a new String with the desired character in place (copying the non-changing parts from the old String).

字符串是不可变的,换句话说,要“替换”字符串中的字符,您必须构建一个具有所需字符的新字符串(复制旧字符串中不变的部分)。

While this seems simple, it has a profound impact on the ability to share between Thread (and objects). One String can safely be shared between Threads without extra checks to see if the String is being changed (which might give a Thread an inconsistency read of the String).

虽然这看起来很简单,但它对在 Thread(和对象)之间共享的能力产生了深远的影响。一个字符串可以安全地在线程之间共享,而无需额外检查字符串是否正在更改(这可能会导致线程读取字符串不一致)。

Other optimizations are also possible, since Strings cannot mutate, you can rewire equality operations to be "equals by value". Which means that a "String factory" can return cached copies of the same String, even when two different String objects are requested, because it will become impossible for the two objects to behave differently.

其他优化也是可能的,因为字符串不能变异,您可以将相等操作重新连接为“按值相等”。这意味着“字符串工厂”可以返回同一个字符串的缓存副本,即使在请求两个不同的 String 对象时也是如此,因为这两个对象不可能有不同的行为。

回答by Shivam

char is a primitive type while String is a class. An array of a specified number of strings and strings are a bundle of characters.

char 是原始类型,而 String 是一个类。由指定数量的字符串组成的数组,字符串是一组字符。