| 1 | package org.jtoolkit.essence.utils; |
| 2 | |
| 3 | import org.jetbrains.annotations.NotNull; |
| 4 | import org.jtoolkit.essence.app.pojo.Datable; |
| 5 | import org.jtoolkit.essence.app.pojo.DatableUtils; |
| 6 | import static org.jtoolkit.essence.app.pojo.impl.DataValueClass.equalsCheckNull; |
| 7 | import org.jtoolkit.essence.concurrency.Immutable; |
| 8 | import org.jtoolkit.essence.data.Mapping; |
| 9 | |
| 10 | import java.io.DataInput; |
| 11 | import java.io.DataOutput; |
| 12 | import java.io.IOException; |
| 13 | |
| 14 | /* |
| 15 | Copyright 2006 Peter Lawrey |
| 16 | |
| 17 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 18 | you may not use this file except in compliance with the License. |
| 19 | You may obtain a copy of the License at |
| 20 | |
| 21 | http://www.apache.org/licenses/LICENSE-2.0 |
| 22 | |
| 23 | Unless required by applicable law or agreed to in writing, software |
| 24 | distributed under the License is distributed on an "AS IS" BASIS, |
| 25 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 26 | See the License for the specific language governing permissions and |
| 27 | limitations under the License. |
| 28 | */ |
| 29 | |
| 30 | /** |
| 31 | * An ordered pair of objects. Useful for key pairs and return value pairs. |
| 32 | * |
| 33 | * @author Peter Lawrey |
| 34 | */ |
| 35 | @Immutable |
| 36 | public class Pair<E1, E2> implements Datable { |
| 37 | private final int hashCode; |
| 38 | public final E1 first; |
| 39 | public final E2 second; |
| 40 | |
| 41 | public Pair(@Immutable E1 first, @Immutable E2 second) { |
| 42 | hashCode = (first == null ? 0 : first.hashCode() * 17) + |
| 43 | (second == null ? 0 : second.hashCode() * 31); |
| 44 | this.first = first; |
| 45 | this.second = second; |
| 46 | } |
| 47 | |
| 48 | public boolean equals(Object obj) { |
| 49 | return obj instanceof Pair && equalsCheckNull(first, ((Pair) obj).first) && equalsCheckNull(second, ((Pair) obj).second); |
| 50 | } |
| 51 | |
| 52 | public int hashCode() { |
| 53 | return hashCode; |
| 54 | } |
| 55 | |
| 56 | static { |
| 57 | DatableUtils.registerBuilder(Pair.class, new Mapping<DataInput, Pair>() { |
| 58 | public Pair convert(DataInput in) throws IOException { |
| 59 | return new Pair<Object, Object>(DatableUtils.readObject(in), DatableUtils.readObject(in)); |
| 60 | } |
| 61 | }); |
| 62 | } |
| 63 | |
| 64 | public void writeData(@NotNull DataOutput out) throws IOException { |
| 65 | DatableUtils.writeObject(out, first); |
| 66 | DatableUtils.writeObject(out, second); |
| 67 | } |
| 68 | } |