Java 打印字符串实例的地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16351555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:26:24  来源:igfitidea点击:

printing the address of the string instances

javastring

提问by

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);
    }
}

in the above piece of code how to print the address of these Strings which i created "Sample1" and "Sample2", i need to print the memory location of the String object myString1 and myString2

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

采纳答案by renz

If you mean "address" as this:

如果你的意思是“地址”是这样的:

System.out.println(new Object());

java.lang.Object@31ec0130

java.lang.Object继承@ 31ec0130

then you can just do,

那么你可以这样做,

String s = new String("one");
System.out.println(Integer.toHexString(s.hashCode()));

1ae66

1ae66

Since what you think is the "address" is just the hashCode() converted to hex string.

由于您认为“地址”只是转换为十六进制字符串的 hashCode() 。



Side Note
This answer was historically accepted as correct and will only work for classes that didn't override the hashCode()method, but (as mentioned in comments) it will not work for Stringclassessince they override the hashCode()method. Readers looking for up-to-date information on the topic of this question should first go through all the comments/discussion on this answer and should consult further resources, or ask a new question citing this question and answer and explicitly asking for new information on things that have changed since they were written.

旁注
此答案历来被认为是正确的,并且仅适用于未覆盖该hashCode()方法的类,但是(如评论中所述)它不适用于String类,因为它们覆盖了该hashCode()方法。寻找有关此问题主题的最新信息的读者应首先浏览有关此答案的所有评论/讨论,并应查阅更多资源,或提出一个引用此问题和答案的新问题,并明确要求提供有关此问题的新信息自从它们被写入以来发生了变化的事情。

回答by clstrfsck

Memory addresses aren't generally available through the Java language, but System.identityHashCode(myString1)might be close enough, depending on what you are trying to achieve.

内存地址通常无法通过 Java 语言获得,但System.identityHashCode(myString1)可能足够接近,具体取决于您要实现的目标。

回答by Aniket Inge

Actually you cannot. JVM handles the memory and the gc can shift the data around when it sees fit.

其实你不能。JVM 处理内存,gc 可以在它认为合适时移动数据。

So there is no "real" concept of a memory address within Java(it only is the concern of the JVM)

所以在 Java 中没有内存地址的“真实”概念(它只是 JVM 的关注点)

回答by hd1

As pointed out my comment, this isn't recommended practise, but since you asked...

正如我的评论指出的那样,这不是推荐的做法,但既然你问...

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);
}

回答by user3346517

simply right ur string name followed by this code:

只需正确的字符串名称后跟此代码:

string object.getClass.getName()+'@'+Integer.toHexString(string boject.hashCode());

example:

例子:

String str=new String("Hello");
System.out.println(str.getClass.getName+'@'+Integer.toHexString(str.hashCode());

回答by chikitin

Why don't you use printf with %b:

为什么不将 printf 与 %b 一起使用:

String s= new String("Hello");
System.out.println(Integer.toHexString(s.hashCode()));
System.out.printf("address of the reference variable s holding string \"%s\" is %h%n", s,s);

回答by AnNik

it seems like you all are INCORRECT! Ill try to explain :

看来你们都是不正确的!我会试着解释:

        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" );

result of this in my case :

在我的情况下的结果:

1372880496
1372880496
false
hi Mr. Buddy

As we see the hashCode() are same, but String has differet addresses (bcs "hi Mr. Buddy" == s >>== false ) ? what do you think ?

正如我们看到的 hashCode() 是相同的,但 String 有不同的地址(bcs "hi Mr. Buddy" == s >>== false )?你怎么看 ?

I found :

我发现 :

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

the result is:

结果是:

s=733003674
..=1626549726

回答by Chintan Pandya

I think answer by @AnNik should be considered as correct answer. Below is the comparison,

我认为@AnNik 的回答应该被视为正确答案。下面是对比,

   String s1= "abc";
    String s2 = new String("abc");
    String s3= "abc";


    System.out.println(Integer.toHexString(s1.hashCode()));
    System.out.println(Integer.toHexString(s2.hashCode()));
    System.out.println(Integer.toHexString(s3.hashCode()));
    System.out.println(System.identityHashCode(s1));
    System.out.println(System.identityHashCode(s2));
    System.out.println(System.identityHashCode(s3));

Output:

输出:

17862
17862
17862
356573597
1735600054
356573597