1 /* 2 * Copyright (C) 2016 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.common.graph; 18 19 import static com.google.common.base.Preconditions.checkNotNull; 20 21 import com.google.common.collect.AbstractIterator; 22 import com.google.common.collect.UnmodifiableIterator; 23 import java.util.AbstractSet; 24 import java.util.Iterator; 25 import java.util.Map; 26 import java.util.Map.Entry; 27 import javax.annotation.CheckForNull; 28 29 /** 30 * A class to represent the set of edges connecting an (implicit) origin node to a target node. 31 * 32 * <p>The {@link #outEdgeToNode} map allows this class to work on networks with parallel edges. See 33 * {@link EdgesConnecting} for a class that is more efficient but forbids parallel edges. 34 * 35 * @author James Sexton 36 * @param <E> Edge parameter type 37 */ 38 @ElementTypesAreNonnullByDefault 39 abstract class MultiEdgesConnecting<E> extends AbstractSet<E> { 40 41 private final Map<E, ?> outEdgeToNode; 42 private final Object targetNode; 43 MultiEdgesConnecting(Map<E, ?> outEdgeToNode, Object targetNode)44 MultiEdgesConnecting(Map<E, ?> outEdgeToNode, Object targetNode) { 45 this.outEdgeToNode = checkNotNull(outEdgeToNode); 46 this.targetNode = checkNotNull(targetNode); 47 } 48 49 @Override iterator()50 public UnmodifiableIterator<E> iterator() { 51 Iterator<? extends Entry<E, ?>> entries = outEdgeToNode.entrySet().iterator(); 52 return new AbstractIterator<E>() { 53 @Override 54 @CheckForNull 55 protected E computeNext() { 56 while (entries.hasNext()) { 57 Entry<E, ?> entry = entries.next(); 58 if (targetNode.equals(entry.getValue())) { 59 return entry.getKey(); 60 } 61 } 62 return endOfData(); 63 } 64 }; 65 } 66 67 @Override 68 public boolean contains(@CheckForNull Object edge) { 69 return targetNode.equals(outEdgeToNode.get(edge)); 70 } 71 } 72