1 7 8 package com.sun.corba.se.impl.orbutil.graph ; 9 10 import java.util.Collection ; 11 import java.util.AbstractSet ; 12 import java.util.Iterator ; 13 import java.util.Map ; 14 import java.util.HashMap ; 15 import java.util.Set ; 16 import java.util.HashSet ; 17 18 public class GraphImpl extends AbstractSet implements Graph 19 { 20 private Map nodeToData ; 21 22 public GraphImpl() 23 { 24 nodeToData = new HashMap () ; 25 } 26 27 public GraphImpl( Collection coll ) 28 { 29 this() ; 30 addAll( coll ) ; 31 } 32 33 34 35 36 37 public boolean add( Object obj ) { 40 if (!(obj instanceof Node)) 41 throw new IllegalArgumentException ( "Graphs must contain only Node instances" ) ; 42 43 Node node = (Node)obj ; 44 boolean found = nodeToData.keySet().contains( obj ) ; 45 46 if (!found) { 47 NodeData nd = new NodeData() ; 48 nodeToData.put( node, nd ) ; 49 } 50 51 return !found ; 52 } 53 54 public Iterator iterator() 56 { 57 return nodeToData.keySet().iterator() ; 58 } 59 60 public int size() 62 { 63 return nodeToData.keySet().size() ; 64 } 65 66 67 68 public NodeData getNodeData( Node node ) 69 { 70 return (NodeData)nodeToData.get( node ) ; 71 } 72 73 private void clearNodeData() 74 { 75 Iterator iter = nodeToData.entrySet().iterator() ; 77 while (iter.hasNext()) { 78 Map.Entry entry = (Map.Entry )iter.next() ; 79 NodeData nd = (NodeData)(entry.getValue()) ; 80 nd.clear( ) ; 81 } 82 } 83 84 interface NodeVisitor 85 { 86 void visit( Graph graph, Node node, NodeData nd ) ; 87 } 88 89 void visitAll( NodeVisitor nv ) 93 { 94 boolean done = false ; 95 96 do { 100 done = true ; 101 102 Map.Entry [] entries = 105 (Map.Entry [])nodeToData.entrySet().toArray( new Map.Entry [0] ) ; 106 107 for (int ctr=0; ctr<entries.length; ctr++) { 111 Map.Entry current = entries[ctr] ; 112 Node node = (Node)current.getKey() ; 113 NodeData nd = (NodeData)current.getValue() ; 114 115 if (!nd.isVisited()) { 116 nd.visited() ; 117 done = false ; 118 119 nv.visit( this, node, nd ) ; 120 } 121 } 122 } while (!done) ; 123 } 124 125 private void markNonRoots() 126 { 127 visitAll( 128 new NodeVisitor() { 129 public void visit( Graph graph, Node node, NodeData nd ) 130 { 131 Iterator iter = node.getChildren().iterator() ; while (iter.hasNext()) { 133 Node child = (Node)iter.next() ; 134 135 graph.add( child ) ; 138 139 NodeData cnd = graph.getNodeData( child ) ; 141 cnd.notRoot() ; 142 } 143 } 144 } ) ; 145 } 146 147 private Set collectRootSet() 148 { 149 final Set result = new HashSet () ; 150 151 Iterator iter = nodeToData.entrySet().iterator() ; 152 while (iter.hasNext()) { 153 Map.Entry entry = (Map.Entry )iter.next() ; 154 Node node = (Node)entry.getKey() ; 155 NodeData nd = (NodeData)entry.getValue() ; 156 if (nd.isRoot()) 157 result.add( node ) ; 158 } 159 160 return result ; 161 } 162 163 public Set getRoots() 164 { 165 clearNodeData() ; 166 markNonRoots() ; 167 return collectRootSet() ; 168 } 169 } 170 | Popular Tags |