打印字符串实例的地址

2022-09-02 02:45:34
package com.testProject;
public class JavaSample {

    public static void main(String[] args) {

        String myString1 = new String("Sample1");
        System.out.println(myString1);
        String myString2 = new String("Sample2");
        System.out.println(myString2);
    }
}

在上面的代码片段中,如何打印我创建的“Sample1”和“Sample2”的这些字符串的地址,我需要打印String对象myString1和myString2的内存位置


答案 1

看来你们都错了!我试着解释:

        String s = new String("hi Mr. Buddy");
//        s = = "hi Mr. Buddy"; //is false
//        s.equals("hi Mr. Buddy"); //is true
        System.out.println( s.hashCode() );
        System.out.println( "hi Mr. Buddy".hashCode() );

        System.out.println( "hi Mr. Buddy" == s );

        System.out.println( "hi Mr. Buddy" );

在我的情况下,结果:

1372880496
1372880496
false
hi Mr. Buddy

正如我们所看到的,hashCode()是相同的,但是字符串具有不同的地址(bcs“hi Mr. Buddy” == s >>== false)?你觉得怎么样?

我发现:

System.out.println( "s=" + System.identityHashCode( s ) );
System.out.println( "..=" + System.identityHashCode( "hi Mr. Buddy" ) );

结果是:

s=733003674
..=1626549726

答案 2

正如我所指出的,这不是推荐的做法,但是既然你问了......

private static Unsafe unsafe;

static
{
    try
    {
        Field field = Unsafe.class.getDeclaredField("theUnsafe");
        field.setAccessible(true);
        unsafe = (Unsafe)field.get(null);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

public static long addressOf(Object o)
throws Exception
{
    Object[] array = new Object[] {o};

    long baseOffset = unsafe.arrayBaseOffset(Object[].class);
    int addressSize = unsafe.addressSize();
    long objectAddress;
    switch (addressSize)
    {
        case 4:
            objectAddress = unsafe.getInt(array, baseOffset);
            break;
        case 8:
            objectAddress = unsafe.getLong(array, baseOffset);
            break;
        default:
            throw new Error("unsupported address size: " + addressSize);
    }       

    return(objectAddress);
}