简体   繁体   English

Java String类在内部如何工作?

[英]How does the Java String class work internally?

In my programming class we are creating a class that resembles the Java String class. 在我的编程类中,我们正在创建一个类似于Java String类的类。 Right now, we create a new object like this : 现在,我们创建一个像这样的新对象:

MyString string = new MyString("Hello World");

Which is fine and all, but in Java you can create a new String object like this: 一切都很好,但是在Java中,您可以创建一个新的String对象,如下所示:

String string = "Hello World";

Is there someway to emulate that? 有办法模仿吗? Isn't this what people call immutable, where you can change the object after you create it, and add on to the object? 这不是人们所说的不可变的,您可以在创建对象后更改它并添加到该对象上吗?

Edit: Apparently I need to go back to English class. 编辑:显然我需要回到英语课。 The 'Im' in immutable means 'not'... Oops, I meant mutable. “我”一词的不变是“不是”……糟糕,我的意思是可变的。

Being "immutable" is actually the opposite of what you describe; “不变”实际上与您所描述的相反。 it means the object cannot be changed after creation or added to. 这意味着对象在创建或添加后无法更改。

Regardless, this has nothing to do with immutability. 无论如何,这与不变性无关。 There is no way to emulate that construction for your own classes. 没有办法为您自己的类模拟这种构造。 String literals are part of the bare bones specification of the language. 字符串文字是该语言的基本内容的一部分。 Just like we have no operator overloading in Java (and thus have no way to make the compiler interpret + the way we'd like it to), we have no way to make the compiler understand a different set of literals. 就像我们在Java中没有运算符重载(因此也没有办法使编译器解释+我们希望的方式)一样,我们也没有办法使编译器理解一组不同的文字。 They just are what they are. 他们就是他们。

I'm sure there is some brilliant way to modify the JVM and create your own compiler to do what you want, but then you're not really using Java anymore. 我敢肯定,有一些绝妙的方法可以修改JVM并创建自己的编译器以执行所需的操作,但是您实际上不再使用Java。

You can read more about literals in the JLS 3.10 , or the official Oracle tutorials ( this one for String s, this one for actual primitive types). 您可以在JLS 3.10或Oracle官方教程中了解更多有关文字的信息( String为实际基本类型)。

In Java, string literals are instances of the String class. 在Java中,字符串文字 String类的实例。 So in your second example, no conversion takes place. 因此,在第二个示例中,没有任何转换发生。 It has nothing to do with immutability (but you would run into problems if Strings were mutable). 它与不变性无关(但是如果Strings可变,您会遇到问题)。

EDIT: To see how the String class works internally, have a look at its source (OpenJDK). 编辑:要查看String类如何在内部工作,请查看其源代码 (OpenJDK)。

Another example 另一个例子

Integer Int = 5;

OR 要么

Integer Int = new Integer (5);

Both works fine. 两者都很好。

Also the below works as well. 以下内容也适用。

 Integer Int;
 int i = 5;
 Int = i ;

I think this is special behavior for few Types only. 我认为这是仅针对少数类型的特殊行为。 Possibly be the equal operator is overloaded. 可能等于运算符被重载了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM