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

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

问题描述

这是我在面试中遇到的一个问题.

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?

推荐答案

组合相同字符串的过程称为interning",并且很多语言编译器已经这样做了很多年,但并非总是如此.问题的答案,尤其是@GennadyVanin--Novosibirsk 所扩展的答案,取决于语言和编译器的实现.对于 Java,根据 Java 的要求,所有常量字符串都被内嵌语言规范.但这只是常量字符串表达式,并且仅当它们同时编译时.如果您有两个在时间和空间上充分分离的 Java 字符串(例如,编译成单独的 JAR 文件),它们将不是同一个对象.类似地,动态创建的 Java 字符串(例如,各种 toString() 方法的输出)不会被实习,除非该方法通过 String.intern 特别请求它().是的,所有对 interned 字符串的使用都将共享相同的内存位置 - 这就是为什么字符串首先被 interned 的重要原因.

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天全站免登陆