[英]Why is String.intern() a native method?
使此方法本地化的邏輯背后是什么?
與僅使用散列圖制作內部字符串池相比,優點是什么?
看起來有些奇怪,但似乎在非本地代碼中很容易做到:
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;
}
}
// ...
}
那么為什么是本機代碼呢?
看起來用非本地代碼很容易...
你錯了。 根據規范, String.intern()
必須與常量池進行交互,才能滿足“所有文字字符串都應被嵌入”的要求。 用Java代碼無法做到這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.