简体   繁体   English

Java 字符数组转字符串而不创建新对象

[英]Java char array to String without creating new objects

When creating a String like this:创建这样的字符串时:

String s1 = “ABC”

the JVM will look in the String pool if "ABC" exists there and create a new object only if "ABC" doesn't exist yet.如果“ABC”存在,JVM 将在字符串池中查找,并且仅当“ABC”尚不存在时才创建新对象。

So the usage of所以使用

String s1 = new String("ABC")

halts this behavior and will create an object every time.停止这种行为,每次都会创建一个对象。

Now I have a problem when converting a char array to String:现在我在将 char 数组转换为 String 时遇到问题:

private char[] names;
...
@Override
public String toString() {
  return new String(this.names);
}

This will always create a new object.这将始终创建一个新对象。 Can I convert from char array to String without creating a new object each time?我可以从 char 数组转换为 String 而不每次都创建新对象吗?

I know of no way to avoid creating a String object in your toString() , but you can avoid retaining these new strings (all but the first one become eligible for GC after the method execution) by explicitly calling String.intern() :我知道没有办法避免在您的toString()创建String对象,但是您可以通过显式调用String.intern()来避免保留这些新字符串(除了第一个字符串在方法执行后都符合 GC 条件String.intern()

@Override
public String toString() {
    return new String(this.names).intern();
}

And you can test it by repeatedly checking myObject.toString() == myObject.toString() .您可以通过反复检查myObject.toString() == myObject.toString()来测试它。

But before doing this, do yourself a favor and be aware of what you're doing .但在此之前,请帮自己一个忙,并注意自己在做什么 It's possible that generating a string object is the better choice, depending on your main reason for doing this.生成字符串对象可能是更好的选择,这取决于您这样做的主要原因。

If your objective is to reduce memory usage you could also consider what you typically store in char[] names and how you manipulate that member field in other code not shown in your example.如果您的目标是减少内存使用,您还可以考虑通常存储在char[] names以及如何在示例中未显示的其他代码中操作该成员字段。 It may reduce memory to switch from char[] to String .char[]切换到String可能会减少内存。

Java 9 introduced compact strings which reduce the internal storage for Latin String versus those that need UTF16. Java 9 引入了紧凑字符串,与需要 UTF16 的String相比,它减少了拉丁String的内部存储。 Thus in some cases new String(this.names) uses less memory than char[] names as it stores byte[] representation of the same characters - although this incurs expense of an extra object for the String .因此,在某些情况下, new String(this.names)char[] names使用更少的内存,因为它存储相同字符的byte[]表示 - 尽管这会导致String额外对象的开销。 However String may not be suitable representation for your other operations that access names especially if you need to call toCharArray() to get the original format back in order for the application to work as before.但是 String 可能不适合您访问names其他操作,特别是如果您需要调用toCharArray()以获取原始格式以使应用程序像以前一样工作。

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

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