有没有办法在Java中获取内存地址?

时间:2019-11-17 02:31:48

标签: java string memory-address


Even if you have two different strings with the same value, they will have the same hashcode.

This means both variables pointing to different memory location. Is there a way to get memory location?

  

jshell> var a = new String(“ Ranga”)

     

a ==>“范围”

     

jshell> var b =新的String(“ Ranga”)

     

b ==>“范围”

     

jshell> a.hashCode()

     

$ 31 ==> 78727449

     

jshell> b.hashCode()

     

$ 32 ==> 78727449

     

jshell> a == b

     

$ 33 ==>假

1 个答案:

答案 0 :(得分:1)

如果要在更改字符串之前查看字符串的原始hashCode,可以执行以下操作:

String foo = ...some string
System.out.println(System.identityHashCode(foo));

根据hashCode的文档

  

在合理可行的范围内,由Object类定义的hashCode方法确实为不同的对象返回不同的整数。 (通常通过将对象的内部地址转换为整数来实现,但是Java™编程语言不需要此实现技术。)