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