两个具有相同内容的字符串是否会存储在同一个内存位置? [英] will two strings with same content be stored in the same memory location?

查看:164
本文介绍了两个具有相同内容的字符串是否会存储在同一个内存位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在接受采访时遇到的一个问题。

This is a question that I got in an interview.

我将两个字符串定义为

String s1="Java";
String s2="Java";

我的问题是这两个引用是否指向相同的内存位置。通常,当我们创建相同的字符串(没有new关键字)时,内容是否只存储在内存中一次,所有具有相同内容的String对象只是引用相同的位置,而不是冗余地存储字符串Java? s1和s2的哈希码是相同的。但是哈希码是否直接依赖于对象的内存位置?

My question is whether these two references point to the same memory location. In general, when we create identical strings (without new keyword), does the content get stored in the memory only once and all the String objects with the same content just refer to the same location, without storing the string "Java" redundantly ? The hash codes of s1 and s2 are the same. But are hashcodes dependent directly on memory location of the object?

推荐答案

组合相同字符串的过程称为实习,并且已经被许多语言编译器多年来完成,但并非总是如此。这个问题的答案,特别是由@ GennadyVanin - Novosibirsk扩展,取决于语言和编译器的实现。对于Java,所有常量字符串都是按照 Java的要求实现的。语言规范。但这只是常量字符串表达式,并且只有在它们同时编译时才会出现。如果你有两个在时间和空间上充分分开的Java字符串(例如,编译成单独的JAR文件),它们将不是同一个对象。类似地,动态创建的Java字符串(例如,各种 toString()方法的输出)将不会被实现,除非该方法通过特定方式请求它的String.intern()。是的,所有使用的实习字符串将共享相同的内存位置 - 这是字符串首先被实现的主要原因。

The process of combining identical strings is called "interning", and has been done for many years by lots of language compilers, but not always. The answer to the question, especially as expanded by @GennadyVanin--Novosibirsk, depends on the language and the compiler implementation. For Java, all constant strings are interned, as required by the Java Language Specification. But that's only constant string expressions, and only when they're compiled at the same time. If you have two Java strings sufficiently separated in time and space (e.g., compiled into separate JAR files), they will not be the same object. Similarly, dynamically created Java strings (e.g., the output of various toString() methods) won't be interned unless the method specifically requests it via String.intern(). And yes, all uses of an interned string will share the same memory locations - that's a big part of why strings are interned in the first place.

对于其他语言,这是一个更大的问题,但是根据这些答案中的所有信息,我相信你可以在网上研究它。我只想说就如何做到这一点没有普遍的协议。

As to other languages, that's a bigger question, but with all the information in these answers, I'm sure you can research it on the web. Suffice it to say that there is no universal agreement on how this ought to be done.

这篇关于两个具有相同内容的字符串是否会存储在同一个内存位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆