Can we access or query the Java String intern (constant) pool?

前端 未结 1 1447
太阳男子
太阳男子 2020-11-30 11:13

Is there are way to access the contents of the String constant pool within our own program?

Say I have some basic code that does this:

String str1 =         


        
相关标签:
1条回答
  • 2020-11-30 11:49

    You cannot directly access the String intern pool.

    As per Javadocs String intern pool is:

    A pool of strings, initially empty, is maintained privately by the class String.

    However String objects can be added to this pool using String's intern() method.

    java.lang.String.intern() returns an interned String, that is, one that has an entry in the global String pool. If the String is not already in the global String pool, then it will be added.

    Programmatically you can follow this approach:

    1. Declare Set<String> StringConstantPool = new HashSet<String>();
    2. call String.intern()
    3. Add returned String value into this pool StringConstantPool
    0 讨论(0)
提交回复
热议问题