001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.collections4.functors;
018
019import java.io.Serializable;
020
021import org.apache.commons.collections4.Equator;
022
023/**
024 * Default {@link Equator} implementation.
025 *
026 * @param <T>  the types of object this {@link Equator} can evaluate.
027 * @since 4.0
028 * @version $Id: DefaultEquator.html 972421 2015-11-14 20:00:04Z tn $
029 */
030public class DefaultEquator<T> implements Equator<T>, Serializable {
031
032    /** Serial version UID */
033    private static final long serialVersionUID = 825802648423525485L;
034
035    /** Static instance */
036    @SuppressWarnings("rawtypes") // the static instance works for all types
037    public static final DefaultEquator INSTANCE = new DefaultEquator<Object>();
038
039    /**
040     * Hashcode used for <code>null</code> objects.
041     */
042    public static final int HASHCODE_NULL = -1;
043
044    /**
045     * Factory returning the typed singleton instance.
046     *
047     * @param <T>  the object type
048     * @return the singleton instance
049     */
050    @SuppressWarnings("unchecked") // the static instance works for all types
051    public static <T> DefaultEquator<T> defaultEquator() {
052        return (DefaultEquator<T>) DefaultEquator.INSTANCE;
053    }
054
055    /**
056     * Restricted constructor.
057     */
058    private DefaultEquator() {
059        super();
060    }
061
062    /**
063     * {@inheritDoc} Delegates to {@link Object#equals(Object)}.
064     */
065    public boolean equate(final T o1, final T o2) {
066        return o1 == o2 || o1 != null && o1.equals(o2);
067    }
068
069    /**
070     * {@inheritDoc}
071     *
072     * @return <code>o.hashCode()</code> if <code>o</code> is non-
073     *         <code>null</code>, else {@link #HASHCODE_NULL}.
074     */
075    public int hash(final T o) {
076        return o == null ? HASHCODE_NULL : o.hashCode();
077    }
078
079    private Object readResolve() {
080        return INSTANCE;
081    }
082
083}