我认为使用数据结构的组合是合适的.这是一个小例子:
public class ManyToManyMap {
private Map> firstToSecondMap = new HashMap<>();
private Map> secondToFirstMap = new HashMap<>();
public void put(S first, C second) {
if (!firstToSecondMap.containsKey(first)) {
firstToSecondMap.put(first, new HashSet<>());
}
firstToSecondMap.get(first).add(second);
if (!secondToFirstMap.containsKey(second)) {
secondToFirstMap.put(second, new HashSet<>());
}
secondToFirstMap.get(second).add(first);
}
public Set getFirst(S first) {
return firstToSecondMap.get(first);
}
public Set getSecond(C second) {
return secondToFirstMap.get(second);
}
public Set removeByFirst(S first) {
Set itemsToRemove = firstToSecondMap.remove(first);
for (C item : itemsToRemove) {
secondToFirstMap.get(item).remove(first);
}
return itemsToRemove;
}
public Set removeBySecond(C second) {
Set itemsToRemove = secondToFirstMap.remove(second);
for (S item : itemsToRemove) {
firstToSecondMap.get(item).remove(second);
}
return itemsToRemove;
}
}
以下是一个示例用法:
ManyToManyMap mmMap = new ManyToManyMap<>();
mmMap.put("Tom", "Math");
mmMap.put("Tom", "Java");
mmMap.put("Tom", "Java");
mmMap.put("Mary", "Java");
Set coursesByStudent = mmMap.getFirst("Tom"); // Java, Math
Set studentByCourse = mmMap.getSecond("Java"); // Tom, Mary
mmMap.removeByFirst("Tom");
studentByCourse = mmMap.getSecond("Java"); // Mary