我一直想知道如何在Java中实现Set。我们可以实现它就像我们使用LinkedList和一个持有Key和Value的对象(Cell)实现HashMap一样吗?你会如何处理唯一性部分?
答案 0 :(得分:5)
答案 1 :(得分:3)
基本上,Set只是一个只保存键的Map。所以你应该告诉自己有关映射算法的信息。注意:例如,HashSet实际上只是HashMap的适配器。 HashSet的add方法只使用HashMap.put(value,SomeDummyValue)。
答案 2 :(得分:1)
以下是解释上述答案的代码段
public HashSet() { map = new HashMap<>(); }
private transient HashMap<E,Object> map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
// Since PRESENT is a constant, for all keys we have same value in backup HashMap called map.
public Iterator<E> iterator() {
return map.keySet().iterator();
}
答案 3 :(得分:-1)
class HashSetBasicImpl<K> {
static class Entry<K> {
private K key;
private Entry<K> next;
Entry(K key) {
key = key;
next = null;
}
}
private Entry<K>[] entries;
public HashSetBasicImpl() {
// fixed size
map =new Entry[100];
}
public boolean contains(K key) {
int idx = key.hashCode();
Entry<K> start = entries[idx];
while(start != null) {
if(start.key == key) {
return true;
}
start = start.next;
}
return false;
}
public boolean add(K key) {
Entry<K> entry = new Entry(key);
int idx = key.hashCode();
// check if entry exists
if(contains(key)) {
return false;
}
// add as first entry
start = entries[idx];
if(start == null) {
entries[idx]= new Entry(key);
return true;
}
// add as nth entry
Entry prev = null;
while(start != null) {
prev = start;
start = start.next;
}
prev.next = new Entry(key);
return true;
}
}