001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools;
003import java.util.ArrayList;
004import java.util.List;
005
006/**
007 * A pair of objects.
008 * @param <A> Type of first item
009 * @param <B> Type of second item
010 * @since 429
011 */
012public final class Pair<A, B> {
013
014    /**
015     * The first item
016     */
017    public A a;
018
019    /**
020     * The second item
021     */
022    public B b;
023
024    /**
025     * Constructs a new {@code Pair}.
026     * @param a The first item
027     * @param b The second item
028     */
029    public Pair(A a, B b) {
030        this.a = a;
031        this.b = b;
032    }
033
034    @Override
035    public int hashCode() {
036        return a.hashCode() + b.hashCode();
037    }
038
039    @Override
040    public boolean equals(Object other) {
041        if (other instanceof Pair<?, ?>) {
042            Pair<?, ?> o = (Pair<?, ?>) other;
043            return a.equals(o.a) && b.equals(o.b);
044        } else
045            return false;
046    }
047
048    public static <T> List<T> toList(Pair<T, T> p) {
049        List<T> l = new ArrayList<>(2);
050        l.add(p.a);
051        l.add(p.b);
052        return l;
053    }
054
055    public static <T> Pair<T, T> sort(Pair<T, T> p) {
056        if (p.b.hashCode() < p.a.hashCode()) {
057            T tmp = p.a;
058            p.a = p.b;
059            p.b = tmp;
060        }
061        return p;
062    }
063
064    @Override
065    public String toString() {
066        return "<"+a+','+b+'>';
067    }
068
069    /**
070     * Convenient constructor method
071     * @param u The first item
072     * @param v The second item
073     * @return The newly created Pair(u,v)
074     */
075    public static <U, V> Pair<U, V> create(U u, V v) {
076        return new Pair<>(u, v);
077    }
078}