1 /* 2 * Copyright (C) 2011 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 * in compliance with the License. You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software distributed under the License 10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 * or implied. See the License for the specific language governing permissions and limitations under 12 * the License. 13 */ 14 15 package com.google.common.base; 16 17 import com.google.common.annotations.GwtCompatible; 18 import java.io.Serializable; 19 import java.util.Iterator; 20 import javax.annotation.CheckForNull; 21 import org.checkerframework.checker.nullness.qual.Nullable; 22 23 @GwtCompatible(serializable = true) 24 @ElementTypesAreNonnullByDefault 25 final class PairwiseEquivalence<E, T extends @Nullable E> extends Equivalence<Iterable<T>> 26 implements Serializable { 27 final Equivalence<E> elementEquivalence; 28 PairwiseEquivalence(Equivalence<E> elementEquivalence)29 PairwiseEquivalence(Equivalence<E> elementEquivalence) { 30 this.elementEquivalence = Preconditions.checkNotNull(elementEquivalence); 31 } 32 33 @Override doEquivalent(Iterable<T> iterableA, Iterable<T> iterableB)34 protected boolean doEquivalent(Iterable<T> iterableA, Iterable<T> iterableB) { 35 Iterator<T> iteratorA = iterableA.iterator(); 36 Iterator<T> iteratorB = iterableB.iterator(); 37 38 while (iteratorA.hasNext() && iteratorB.hasNext()) { 39 if (!elementEquivalence.equivalent(iteratorA.next(), iteratorB.next())) { 40 return false; 41 } 42 } 43 44 return !iteratorA.hasNext() && !iteratorB.hasNext(); 45 } 46 47 @Override doHash(Iterable<T> iterable)48 protected int doHash(Iterable<T> iterable) { 49 int hash = 78721; 50 for (T element : iterable) { 51 hash = hash * 24943 + elementEquivalence.hash(element); 52 } 53 return hash; 54 } 55 56 @Override equals(@heckForNull Object object)57 public boolean equals(@CheckForNull Object object) { 58 if (object instanceof PairwiseEquivalence) { 59 @SuppressWarnings("unchecked") 60 PairwiseEquivalence<Object, Object> that = (PairwiseEquivalence<Object, Object>) object; 61 return this.elementEquivalence.equals(that.elementEquivalence); 62 } 63 64 return false; 65 } 66 67 @Override hashCode()68 public int hashCode() { 69 return elementEquivalence.hashCode() ^ 0x46a3eb07; 70 } 71 72 @Override toString()73 public String toString() { 74 return elementEquivalence + ".pairwise()"; 75 } 76 77 private static final long serialVersionUID = 1; 78 } 79