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