English 中文(简体)
在java的字符串可重生吗?
原标题:Reusability of Strings in java?
  • 时间:2012-05-25 18:47:00
  •  标签:
  • java
String h = "hi";

这里我们引用的是字符串 h 和字符串 字性 hi。 JVM 拥有一个字符串字性池来存储字符串字性, 这样我们就可以在字符串变换时重新使用这些字符串...

当我们说 repreable, 指的是什么? 我们说的是 address 吗?

最佳回答

是的,为了使事情简单一些,你可以把它看作是从同一个地址选择,但更精确的变量是持有相同的数字/对象 reference ,即JVM 在绘制对象的适当内存地址时使用该数字/对象 (对象可以在内存中移动,但仍具有相同的参考)。

你可以用这样的代码测试它:

String w1 = "word";
String w2 = "word";
String b = new String("word"); // explicitly created String (by `new` operator) 
                               // won t be placed in string pool automatically
System.out.println(w1 == w2);  // true  -> variables hold same reference
System.out.println(w1 == b);   // false -> variable hold different references,
                               // so they represent different objects
b = b.intern(); // checks if pool contains this string, if not puts this string in pool, 
                // then returns reference of string from pool and stores it in `b` variable
System.out.println(w1 == b);   // true  -> now b holds same reference as w1
问题回答

遇有

String h = "hi";
String i = "hi";
String j = new String("hi");

依 JDK 版本而定, 编译者 < 坚固> may 做所谓的< a href=" http://www.codeintrctions.com/2009/01/busting-javalangstringinter- myths.html" rel="nofollow"\\\ pargy > interning , 创建一个表示 "hi" 的字节数据的单一实例, 并将其再用于变量引用。 在最新的规格中, 所有 < a href=" http://docs.oracle.com/javase/specs/jls/ se5.0/html/lexical.html#3.10.5" rel="nofolpol" > string < meng > > > astreng > literalals

使用上一个语句中的 new 关键词,将创建一个完全相同的字节为单独对象的 < strong> new situation 。

字符串库中创建的字符串对象在<强年时间> <强年> <强年 > 不 除非调用 .intern ()

h == i; // true
h == j; // false
j.intern();
h == j; // true

意思是,如果20个物体使用相同的字面字符串:

private String h = "hi";

所有这些对象实际上都会在内存中引用相同的字符串实例。 这并不重要, 因为无法更改字符串的内容, 因为字符串的内容是不可改变的。 因此相同的实例可以在对象之间没有问题的情况下共享 。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...