1/* 2 * Copyright (C) 2010 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 17package com.google.common.base; 18 19import com.google.common.annotations.Beta; 20import com.google.common.annotations.GwtCompatible; 21 22import java.io.Serializable; 23 24/** 25 * Contains static factory methods for creating {@code Equivalence} instances. 26 * 27 * <p>All methods return serializable instances. 28 * 29 * @author Bob Lee 30 * @author Kurt Alfred Kluever 31 * @author Gregory Kick 32 * @since 4.0 33 */ 34@Beta 35@GwtCompatible 36public final class Equivalences { 37 private Equivalences() {} 38 39 /** 40 * Returns an equivalence that delegates to {@link Object#equals} and {@link Object#hashCode}. 41 * {@link Equivalence#equivalent} returns {@code true} if both values are null, or if neither 42 * value is null and {@link Object#equals} returns {@code true}. {@link Equivalence#hash} returns 43 * {@code 0} if passed a null value. 44 * 45 * @since 8.0 (present null-friendly behavior) 46 * @since 4.0 (otherwise) 47 */ 48 public static Equivalence<Object> equals() { 49 return Equals.INSTANCE; 50 } 51 52 /** 53 * Returns an equivalence that uses {@code ==} to compare values and {@link 54 * System#identityHashCode(Object)} to compute the hash code. {@link Equivalence#equivalent} 55 * returns {@code true} if {@code a == b}, including in the case that a and b are both null. 56 */ 57 public static Equivalence<Object> identity() { 58 return Identity.INSTANCE; 59 } 60 61 private static final class Equals extends Equivalence<Object> 62 implements Serializable { 63 64 static final Equals INSTANCE = new Equals(); 65 66 @Override protected boolean doEquivalent(Object a, Object b) { 67 return a.equals(b); 68 } 69 @Override public int doHash(Object o) { 70 return o.hashCode(); 71 } 72 73 private Object readResolve() { 74 return INSTANCE; 75 } 76 private static final long serialVersionUID = 1; 77 } 78 79 private static final class Identity extends Equivalence<Object> 80 implements Serializable { 81 82 static final Identity INSTANCE = new Identity(); 83 84 @Override protected boolean doEquivalent(Object a, Object b) { 85 return false; 86 } 87 88 @Override protected int doHash(Object o) { 89 return System.identityHashCode(o); 90 } 91 92 private Object readResolve() { 93 return INSTANCE; 94 } 95 private static final long serialVersionUID = 1; 96 } 97} 98