Java获取对象内存地址
haseCode()方法获取并非对象内存地址
hashCode方法的主要作用是为了配合基于散列的集合一起正常运行,获取对象散列的地址,并非实际内存地址。
java直接打印对象,结果是十六进制的散列地址值
public class ObjectTest { public static void main(String[] args) { Object obj = new Object(); System.out.println(obj); System.out.println(Integer.toHexString(obj.hashCode(); } }
haseCode()方法无法证明两个对象是否为同一个对象
public class ObjectTest { public static void main(String[] args) { String s1 = "hello"; String s2 = new String("hello"); System.out.println(s1.hashCode()); System.out.println(s2.hashCode()); } }
打印的值都相等,无法区分两个不同的对象
Java 如何获取对象内存地址
maven引入jol工具包
<dependency> <groupId>org.openjdk.jol</groupId> <artifactId>jol-core</artifactId> <version>0.9</version> </dependency>
示例代码
public class ObjectTest { public static void main(String[] args) { String s1 = "hello"; String s2 = new String("hello"); System.out.println(s1==s2); System.out.println(s1.equals(s2)); System.out.println("--获取内存地址--"); System.out.println(VM.current().addressOf(s1)); System.out.println(VM.current().addressOf(s2)); } }
上一篇:
IDEA上Java项目控制台中文乱码