Java 为什么 String 没有原始类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2099257/
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-13 03:32:07  来源:igfitidea点击:

Why is there no primitive type for String?

javastringprimitive-types

提问by user241924

Why doesn't Java have a primitive type for String when most of the other data types do?

当大多数其他数据类型都有时,为什么 Java 没有 String 的原始类型?

采纳答案by Jon

String is an object, it isn't a primitive type at all, just an array of chars. The reason why primitive types exist in Java at all is an interesting one, excerpt from a James Gosling interview:

String 是一个对象,它根本不是原始类型,只是一个字符数组。Java 中存在原始类型的原因很有趣,摘自James Gosling 的采访

Bill Venners:Why are there primitive types in Java? Why wasn't everything just an object?

James Gosling:Totally an efficiency thing. There are all kinds of people who have built systems where ints and that are all objects. There are a variety of ways to do that, and all of them have some pretty serious problems. Some of them are just slow, because they allocate memory for everything. Some of them try to do objects where sometimes they are objects, sometimes they are not (which is what the standard LISP system did), and then things get really weird. It kind of works, but it's strange.

Just making it such that there are primitive and objects, and they're just different. You solve a whole lot of problems.

Bill Venners:为什么 Java 中有原始类型?为什么不是一切都只是一个对象?

James Gosling:完全是一个效率问题。有各种各样的人构建了系统,其中 int 和所有对象都是对象。有多种方法可以做到这一点,但它们都有一些非常严重的问题。其中一些只是很慢,因为它们为所有内容分配内存。他们中的一些人尝试做对象,有时它们是对象,有时它们不是(这是标准 LISP 系统所做的),然后事情变得非常奇怪。它有点工作,但很奇怪。

只是让它有原始和对象,它们只是不同的。你解决了很多问题。

So in short the primitive types exist for efficiency reasons.

所以简而言之,原始类型是出于效率原因而存在的。

回答by Eric Mickelsen

Most programming languages don't consider a string primitive because it's actually an array of characters. Primitive types almost always have a fixed size.

大多数编程语言不考虑字符串原语,因为它实际上是一个字符数组。原始类型几乎总是有固定的大小。

I should say though that some people might consider String to be "primitive" because it is built-in. But it's not primitive in the sense of being a basic type as opposed to a composite type. Because a string is an array of characters, it is a composite type.

我应该说,虽然有些人可能认为 String 是“原始的”,因为它是内置的。但在作为基本类型而不是复合类型的意义上,它不是原始类型。因为字符串是一个字符数组,所以它是一种复合类型。

回答by Yin Zhu

int, char, float, double, etc. all have a fixed length in memory. e.g. a int have 4 bytes, thus 32bits.

int、char、float、double 等在内存中都有固定长度。例如一个 int 有 4 个字节,因此是 32 位。

but a string can have different length, it is actually an array of char.

但是一个字符串可以有不同的长度,它实际上是一个字符数组。