package Sequenic.T2ext.Selection; import java.util.Map; import java.util.WeakHashMap; /** * This will return a new Object with the given hashCode. * The equals method is overridden so that it will return true * when compared to any Object with the same hashCode. * * Note that the contract of equals will only be satisfied if the other object * also overrides equals in the same manner. * * I.e. a.equals(b) if and only if b.equals(a), thus the other object must have a * similarly defined equals method. * * @author Jeiel Schalkwijk * */ class HashEqualsEdge { /** This int is returned by hashCode. * It is interpreted by toString as an edge where the most-significant 16 bits * encode the source node id as an unsigned short (i.e. in range [0,65535]) and the least-significant 16 bits * encode the destination node id in the same manner. */ protected int edge; protected HashEqualsEdge(){}; private HashEqualsEdge(final int edge){ this.edge = edge;} public int fst() { return edge >>> 16; } public int snd() { return edge & 65535; } @Override public int hashCode() { return edge; } @Override public boolean equals(Object obj) { return edge==obj.hashCode(); } @Override public String toString() { return "("+fst()+","+snd()+")"; } /** * A factory to create HashEqualsEdge objects. * It uses a WeakHashMap to maintain a cache of canonical instances in order to avoid * creating duplicate instances of existing edges. * * @author Jeiel Schalkwijk * */ static final class CanonicalMappings extends HashEqualsEdge { private final Map canonMappings = new WeakHashMap(); final synchronized HashEqualsEdge make(final int edge) { this.edge = edge; HashEqualsEdge res = canonMappings.get(this); if(res==null) { res = new HashEqualsEdge(edge); canonMappings.put(res, res); } return res; } final HashEqualsEdge make(int srcId, int dstId) { return make((srcId << 16 ) | dstId); } } /** Because the make method is synchronized, a single global weakCache can be shared. */ static final CanonicalMappings weakCache = new CanonicalMappings(); }