简体   繁体   English

为什么String.intern()是本机方法?

[英]Why is String.intern() a native method?

What's the logic behind making this method native? 使此方法本地化的逻辑背后是什么?

What is the advantage over just making the interned String pool with a hash map? 与仅使用散列图制作内部字符串池相比,优点是什么?

It looks a little strange, but it seems like it'd be pretty easy to do in non-native code: 看起来有些奇怪,但似乎在非本地代码中很容易做到:

import java.util.HashMap;

public class String {

    // ...

    private final static HashMap<String, String> pool = new HashMap<>();

    public String intern() {

        if (pool.containsKey(this))
            return pool.get(this);

        synchronized (pool) {
            if (pool.containsKey(this))
                return pool.get(this);
            pool.put(this, this);
            return this;
        }

    }

    // ...

}

So why is it native code then? 那么为什么是本机代码呢?

It seems like it'd be pretty easy to do in non-native code ... 看起来用非本地代码很容易...

You're wrong. 你错了。 By specification, String.intern() must interact with the constant pool, to meet the requirement that 'all literal strings are interned'. 根据规范, String.intern()必须与常量池进行交互,才能满足“所有文字字符串都应被嵌入”的要求。 That can't be done from Java code. 用Java代码无法做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM