I have class ID and Value, and a Map from ID to Value
public class IDs {
public TreeSet<Integer> ids;
public HashSet<IDs> neighbors;
public static HashSet<IDs> idSet = new HashSet<>();
private boolean hash;
private int hashcode;
public IDs(int id,HashSet<IDs> neighbors) {
this.ids = new TreeSet<>();
this.ids.add(id);
this.neighbors = neighbors;
idSet.add(this);
this.hash = false;
this.hashcode = 0;
}
public void addNeighbor(IDs neighbor) {
this.neighbors.add(neighbor);
neighbor.neighbors.add(this);
}
public static boolean cluster(IDs id1,IDs id2) {
if (id1.equals(id2))
return false;
id1.ids.addAll(id2.ids);
id2.ids.addAll(id1.ids);
id2.neighbors.remove(id1);
id1.neighbors.remove(id2);
id1.neighbors.addAll(id2.neighbors);
id2.neighbors.addAll(id1.neighbors);
id1.hash = false;
return true;
}
@Override
public String toString() {
String name = "{";
for (Integer i:ids)
name += "Cell " + i + ", ";
name += "}";
return name;
}
@Override
public boolean equals(Object obj) {
IDs o = (IDs) obj;
return this.ids.containsAll(o.ids) && o.ids.containsAll(this.ids);
}
@Override
public int hashCode() {
if (this.hash)
return this.hashcode;
TreeSet temp = (TreeSet) this.ids.clone();
int first,hash = 0;
while (!temp.isEmpty()) {
first = (int) temp.first();
temp.remove(temp.first());
hash = CantorPair(hash,first);
}
this.hash = true;
this.hashcode = hash;
return hash;
}
private int CantorPair(int k1,int k2) {
return (k1 + k2) * (k1 + k2 + 1) / 2 + k2;
}
}
class Value{
Integer value;
}
Map<ID,Value> map = new Map<>();
Now I want to merge entries together, new value is the sum of old values, but what I have created are entries with duplicate keys and old values instead. Anyone has any idea how to solve this?
EDIT1: I overrode the equals()
and hashCode()
already, sorry for not showing it here, the Map still have duplicate key entries!
EDIT2: I have uploaded the full code of my class for the keys