SAr1t SAr1t
Знаток
(398)
1 год назад
public class SimpleHashSet {
private static final int INITIAL_CAPACITY = 16;
private static final float LOAD_FACTOR = 0.75f;
private Entry[] table;
private int size;
public SimpleHashSet() {
this.table = new Entry[INITIAL_CAPACITY];
this.size = 0;
}
public boolean add(Object value) {
if (contains(value)) {
return false;
}
if (size >= table.length * LOAD_FACTOR) {
resize();
}
int index = hash(value);
Entry entry = new Entry(value);
entry.next = table[index];
table[index] = entry;
size++;
return true;
}
public boolean remove(Object value) {
int index = hash(value);
Entry prev = null;
Entry curr = table[index];
while (curr != null) {
if (curr.value.equals(value)) {
if (prev == null) {
table[index] = curr.next;
} else {
prev.next = curr.next;
}
size--;
return true;
}
prev = curr;
curr = curr.next;
}
return false;
}
public boolean contains(Object value) {
int index = hash(value);
Entry entry = table[index];
while (entry != null) {
if (entry.value.equals(value)) {
return true;
}
entry = entry.next;
}
return false;
}
public int size() {
return size;
}
private void resize() {
Entry[] oldTable = table;
table = new Entry[table.length * 2];
size = 0;
for (Entry entry : oldTable) {
while (entry != null) {
add(entry.value);
entry = entry.next;
}
}
}
private int hash(Object value) {
return Math.abs(value.hashCode() % table.length);
}
private static class Entry {
Object value;
Entry next;
public Entry(Object value
) {
this.value = value;
this.next = null;
}
}
}
Возможно не все примеры будут работать, но в целом можно отсюда отталкиваться