View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.collections4.functors;
18  
19  import java.io.Serializable;
20  import java.util.Objects;
21  
22  import org.apache.commons.collections4.Equator;
23  
24  /**
25   * Default {@link Equator} implementation.
26   *
27   * @param <T>  the types of object this {@link Equator} can evaluate.
28   * @since 4.0
29   */
30  public class DefaultEquator<T> implements Equator<T>, Serializable {
31  
32      /** Serial version UID */
33      private static final long serialVersionUID = 825802648423525485L;
34  
35      /** Static instance */
36      @SuppressWarnings("rawtypes") // the static instance works for all types
37      public static final DefaultEquator INSTANCE = new DefaultEquator<>();
38  
39      /**
40       * Hashcode used for {@code null} objects.
41       */
42      public static final int HASHCODE_NULL = -1;
43  
44      /**
45       * Factory returning the typed singleton instance.
46       *
47       * @param <T>  the object type
48       * @return the singleton instance
49       */
50      public static <T> DefaultEquator<T> defaultEquator() {
51          return DefaultEquator.INSTANCE;
52      }
53  
54      /**
55       * Restricted constructor.
56       */
57      private DefaultEquator() {
58      }
59  
60      /**
61       * {@inheritDoc} Delegates to {@link Objects#equals(Object, Object)}.
62       */
63      @Override
64      public boolean equate(final T o1, final T o2) {
65          return Objects.equals(o1, o2);
66      }
67  
68      /**
69       * {@inheritDoc}
70       *
71       * @return {@code o.hashCode()} if {@code o} is non-
72       *         {@code null}, else {@link #HASHCODE_NULL}.
73       */
74      @Override
75      public int hash(final T o) {
76          return o == null ? HASHCODE_NULL : o.hashCode();
77      }
78  
79      private Object readResolve() {
80          return INSTANCE;
81      }
82  
83  }