【发布时间】:2014-07-27 01:02:59
【问题描述】:
我正在实现我发现的 Hashtable 功能 http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Hashtable.java.
我逐字逐句输入了整个源代码。但是,Eclipse 给了我三个错误:
The method synchronizedSet(Set<T>, Object) from the type Collections is not visibleThe method synchronizedCollection(Collection<T>, Object) from the type Collections is not visibleA duplicate error when calling synchronizedSet() again
这是错误所在的代码:
public Set<K> keySet(){
if (keySet == null)
keySet = Collections.synchronizedSet(new KeySet(), this);
return keySet;
}
private class KeySet extends AbstractSet<K> {
public Iterator<K> iterator(){
return getIterator(KEYS);
}
public int size(){
return count;
}
public boolean contains(Object o){
return containsKey(o);
}
public boolean remove(Object o){
return HashTable.this.remove(o) != null;
}
public void clear(){
HashTable.this.clear();
}
}
public Set<Map.Entry<K, V>> entrySet(){
if (entrySet == null)
entrySet = Collections.synchronizedSet(new EntrySet(), this);
return entrySet;
}
private class EntrySet extends AbstractSet<Map.Entry<K, V>> {
public Iterator<Map.Entry<K,V>> iterator(){
return getIterator(ENTRIES);
}
public boolean add(Map.Entry<K,V> o) {
return super.add(o);
}
public boolean contains(Object o){
if (!(o instanceof Map.Entry))
return false;
Map.Entry entry = (Map.Entry)o;
Object key = entry.getKey();
Entry[] tab = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFF) % tab.length;
for (Entry e = tab[index]; e != null; e = e.next)
if (e.hash == hash && e.equals(entry))
return true;
return false;
}
public boolean remove(Object o){
if (!(o instanceof Map.Entry))
return false;
Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
K key = entry.getKey();
Entry[] tab = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFF) % tab.length;
for (Entry<K, V> e = tab[index], prev = null; e != null; prev = e, e = e.next){
if (e.hash == hash && e.equals(entry)){
modCount++;
if (prev != null)
prev.next = e.next;
else
tab[index] = e.next;
count--;
e.value = null;
return true;
}
}
return false;
}
public int size(){
return count;
}
public void clear(){
HashTable.this.clear();
}
}
public Collection<V> values(){
if (values == null)
values = Collections.synchronizedCollection(new ValueCollection(), this);
return values;
}
我已经查看了Collections 源代码以及Set 源代码,并在我的一生中找到了解决方案。
【问题讨论】: