Π ΡΡΠΌ ΠΏΡΠΎΠ±Π»Π΅ΠΌΠ°?
package com.javarush.task.task37.task3707;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.*;
public class AmigoSet<E> extends AbstractSet<E> implements Serializable, Cloneable, Set<E> {
private static final Object PRESENT = new Object();
private transient HashMap<E,Object> map;
public AmigoSet() {
map = new HashMap<>();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public boolean containsAll(Collection<?> c) {
return map.containsKey(c);
}
@Override
public Object clone() throws CloneNotSupportedException {
try {
AmigoSet<E> clone = (AmigoSet<E>) super.clone();
clone.map = (HashMap<E, Object>) map.clone();
return clone;
} catch (Exception e) {
throw new InternalError();
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
AmigoSet<?> amigoSet = (AmigoSet<?>) o;
return Objects.equals(map, amigoSet.map);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), map);
}
@Override
public boolean remove(Object o) {
return super.remove(o);
}
@Override
public void clear() {
map.clear();
}
public AmigoSet(Collection<? extends E> collection) {
this.map = new HashMap<>(Math.max((int) (collection.size() / .75f) + 1, 16));
addAll(collection);
}
@Override
public Iterator<E> iterator() {
return map.keySet().iterator();
}
@Override
public int size() {
return map.size();
}
@Override
public boolean add(E e) {
return map.put(e, PRESENT) == null;
}
private void writeObject(ObjectOutputStream s) throws java.io.IOException {
s.defaultWriteObject();
int capacity = HashMapReflectionHelper.callHiddenMethod(map, "capacity");
int loadFactor = HashMapReflectionHelper.callHiddenMethod(map, "loadFactor");
s.writeInt(capacity);
s.writeInt(loadFactor);
s.writeInt(map.size());
if (map.size() == size()) {
for (E e : map.keySet())
s.writeObject(e);
}
}
private void readObject(ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
s.readObject();
int capacity = s.readInt();
int loadFactor = s.readInt();
map = new HashMap<>(capacity, loadFactor);
int size = s.readInt();
if (map.size() == size) {
for (int i = 0; i < size; i++) {
E e = (E) s.readObject();
map.put(e, PRESENT);
}
}
}
}