001: /*
002: *******************************************************************************
003: * Copyright (C) 1996-2005, International Business Machines Corporation and *
004: * others. All Rights Reserved. *
005: *******************************************************************************
006: */
007: package com.ibm.icu.dev.test.util;
008:
009: import java.util.Collections;
010: import java.util.HashMap;
011: import java.util.HashSet;
012: import java.util.Iterator;
013: import java.util.Set;
014:
015: /**
016: * Everything that maps to the same value is part of the same equivalence class
017: * @author davis
018: *
019: */
020: public class XEquivalenceMap {
021: HashMap source_target = new HashMap();
022: HashMap target_sourceSet = new HashMap();
023: HashMap source_Set = new HashMap();
024:
025: public XEquivalenceMap clear() {
026: source_target.clear();
027: target_sourceSet.clear();
028: source_Set.clear();
029: return this ;
030: }
031:
032: public XEquivalenceMap add(Object source, Object target) {
033: Object otherTarget = source_target.get(source);
034: if (otherTarget != null) {
035: if (otherTarget.equals(target))
036: return this ;
037: throw new IllegalArgumentException(
038: "Same source mapping to different targets: "
039: + source + " => " + otherTarget + " & "
040: + target);
041: }
042: source_target.put(source, target);
043: Set s = (Set) target_sourceSet.get(target);
044: if (s == null)
045: target_sourceSet.put(target, s = new HashSet());
046: s.add(source);
047: source_Set.put(source, s);
048: return this ;
049: }
050:
051: public Set getEquivalences(Object source) {
052: Set s = (Set) source_Set.get(source);
053: if (s == null)
054: return null;
055: return Collections.unmodifiableSet(s);
056: }
057:
058: public boolean areEquivalent(Object source1, Object source2) {
059: Set s = (Set) source_Set.get(source1);
060: if (s == null)
061: return false;
062: return s.contains(source2);
063: }
064:
065: public Object getTarget(Object source) {
066: return source_target.get(source);
067: }
068:
069: public Set getSources(Object target) {
070: Set s = (Set) target_sourceSet.get(target);
071: return Collections.unmodifiableSet(s);
072: }
073:
074: public Iterator iterator() {
075: MyIterator result = new MyIterator();
076: result.target_sourceSet_iterator = target_sourceSet.keySet()
077: .iterator();
078: return result;
079: }
080:
081: public int size() {
082: return target_sourceSet.size();
083: }
084:
085: private class MyIterator implements Iterator {
086: private Iterator target_sourceSet_iterator;
087:
088: public void remove() {
089: throw new UnsupportedOperationException();
090: }
091:
092: public boolean hasNext() {
093: return target_sourceSet_iterator.hasNext();
094: }
095:
096: public Object next() {
097: return getSources(target_sourceSet_iterator.next());
098: }
099: }
100: }
|