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.lang3.tuple;
18  
19  import java.io.Serializable;
20  import java.util.Map;
21  
22  import org.apache.commons.lang3.ObjectUtils;
23  import org.apache.commons.lang3.builder.CompareToBuilder;
24  
25  /**
26   * <p>A pair consisting of two elements.</p>
27   * 
28   * <p>This class is an abstract implementation defining the basic API.
29   * It refers to the elements as 'left' and 'right'. It also implements the
30   * {@code Map.Entry} interface where the key is 'left' and the value is 'right'.</p>
31   * 
32   * <p>Subclass implementations may be mutable or immutable.
33   * However, there is no restriction on the type of the stored objects that may be stored.
34   * If mutable objects are stored in the pair, then the pair itself effectively becomes mutable.</p>
35   *
36   * @param <L> the left element type
37   * @param <R> the right element type
38   *
39   * @since Lang 3.0
40   */
41  public abstract class Pair<L, R> implements Map.Entry<L, R>, Comparable<Pair<L, R>>, Serializable {
42  
43      /** Serialization version */
44      private static final long serialVersionUID = 4954918890077093841L;
45  
46      /**
47       * <p>Obtains an immutable pair of from two objects inferring the generic types.</p>
48       * 
49       * <p>This factory allows the pair to be created using inference to
50       * obtain the generic types.</p>
51       * 
52       * @param <L> the left element type
53       * @param <R> the right element type
54       * @param left  the left element, may be null
55       * @param right  the right element, may be null
56       * @return a pair formed from the two parameters, not null
57       */
58      public static <L, R> Pair<L, R> of(final L left, final R right) {
59          return new ImmutablePair<L, R>(left, right);
60      }
61  
62      //-----------------------------------------------------------------------
63      /**
64       * <p>Gets the left element from this pair.</p>
65       * 
66       * <p>When treated as a key-value pair, this is the key.</p>
67       * 
68       * @return the left element, may be null
69       */
70      public abstract L getLeft();
71  
72      /**
73       * <p>Gets the right element from this pair.</p>
74       * 
75       * <p>When treated as a key-value pair, this is the value.</p>
76       * 
77       * @return the right element, may be null
78       */
79      public abstract R getRight();
80  
81      /**
82       * <p>Gets the key from this pair.</p>
83       * 
84       * <p>This method implements the {@code Map.Entry} interface returning the
85       * left element as the key.</p>
86       * 
87       * @return the left element as the key, may be null
88       */
89      @Override
90      public final L getKey() {
91          return getLeft();
92      }
93  
94      /**
95       * <p>Gets the value from this pair.</p>
96       * 
97       * <p>This method implements the {@code Map.Entry} interface returning the
98       * right element as the value.</p>
99       * 
100      * @return the right element as the value, may be null
101      */
102     @Override
103     public R getValue() {
104         return getRight();
105     }
106 
107     //-----------------------------------------------------------------------
108     /**
109      * <p>Compares the pair based on the left element followed by the right element.
110      * The types must be {@code Comparable}.</p>
111      * 
112      * @param other  the other pair, not null
113      * @return negative if this is less, zero if equal, positive if greater
114      */
115     @Override
116     public int compareTo(final Pair<L, R> other) {
117       return new CompareToBuilder().append(getLeft(), other.getLeft())
118               .append(getRight(), other.getRight()).toComparison();
119     }
120 
121     /**
122      * <p>Compares this pair to another based on the two elements.</p>
123      * 
124      * @param obj  the object to compare to, null returns false
125      * @return true if the elements of the pair are equal
126      */
127     @SuppressWarnings( "deprecation" ) // ObjectUtils.equals(Object, Object) has been deprecated in 3.2
128     @Override
129     public boolean equals(final Object obj) {
130         if (obj == this) {
131             return true;
132         }
133         if (obj instanceof Map.Entry<?, ?>) {
134             final Map.Entry<?, ?> other = (Map.Entry<?, ?>) obj;
135             return ObjectUtils.equals(getKey(), other.getKey())
136                     && ObjectUtils.equals(getValue(), other.getValue());
137         }
138         return false;
139     }
140 
141     /**
142      * <p>Returns a suitable hash code.
143      * The hash code follows the definition in {@code Map.Entry}.</p>
144      * 
145      * @return the hash code
146      */
147     @Override
148     public int hashCode() {
149         // see Map.Entry API specification
150         return (getKey() == null ? 0 : getKey().hashCode()) ^
151                 (getValue() == null ? 0 : getValue().hashCode());
152     }
153 
154     /**
155      * <p>Returns a String representation of this pair using the format {@code ($left,$right)}.</p>
156      * 
157      * @return a string describing this object, not null
158      */
159     @Override
160     public String toString() {
161         return new StringBuilder().append('(').append(getLeft()).append(',').append(getRight()).append(')').toString();
162     }
163 
164     /**
165      * <p>Formats the receiver using the given format.</p>
166      * 
167      * <p>This uses {@link java.util.Formattable} to perform the formatting. Two variables may
168      * be used to embed the left and right elements. Use {@code %1$s} for the left
169      * element (key) and {@code %2$s} for the right element (value).
170      * The default format used by {@code toString()} is {@code (%1$s,%2$s)}.</p>
171      * 
172      * @param format  the format string, optionally containing {@code %1$s} and {@code %2$s}, not null
173      * @return the formatted string, not null
174      */
175     public String toString(final String format) {
176         return String.format(format, getLeft(), getRight());
177     }
178 
179 }