0

我写了一个简单的类(StringPools 本身的优点不是我的问题;我想要这个类有特定的原因):

import java.lang.ref.WeakReference;
import java.util.WeakHashMap;

public final class StringPool {

    private WeakHashMap m_pool = new WeakHashMap();

    public String intern(String s) {
        WeakReference reference = (WeakReference)m_pool.get(s);
        if(reference != null) {
            String interned = (String)reference.get();
            if(interned != null)
                return interned;
        }
        m_pool.put(s,new WeakReference(s));
        return s;
    }
};

当我编译它时,编译器指出它使用未经检查或不安全的操作:

warning: [unchecked] unchecked call to WeakReference(T) as a member of the raw type WeakReference       
    m_pool.put(s,new WeakReference(s));
    ^   where T is a type-variable:
    T extends Object declared in class WeakReference 

warning: [unchecked] unchecked call to put(K,V) as a member of the raw type WeakHashMap 
    m_pool.put(s,new WeakReference(s));
    ^   where K,V are type-variables:
    K extends Object declared in class WeakHashMap
    V extends Object declared in class WeakHashMap

2 warnings

我应该如何修复这些警告,以便代码编译干净并且正确?

4

2 回答 2

1

使用泛型:

public final class StringPool {

    private WeakHashMap<String, WeakReference<String>> m_pool = new WeakHashMap<String, WeakReference<String>>();

    public String intern(String s) {
        WeakReference<String> reference = m_pool.get(s);
        if (reference != null) {
            String interned = reference.get();
            if (interned != null)
                return interned;
        }
        m_pool.put(s, new WeakReference<String>(s));
        return s;
    }
};
于 2012-08-16T07:46:13.010 回答
1

添加泛型:

WeakHashMap<String, WeakReference<String>>

从以下位置删除铸件:

(WeakReference)m_pool.get(s);

和:

(String)reference.get()

看起来像:

m_pool.get(s);

reference.get()

各自。

于 2012-08-16T07:45:27.873 回答