001// Copyright (c) FIRST and other WPILib contributors. 002// Open Source Software; you can modify and/or share it under the terms of 003// the WPILib BSD license file in the root directory of this project. 004 005package edu.wpi.first.math; 006 007import java.util.Objects; 008 009/** 010 * Represents a pair of two objects. 011 * 012 * @param <A> The first object's type. 013 * @param <B> The second object's type. 014 */ 015public class Pair<A, B> { 016 private final A m_first; 017 private final B m_second; 018 019 /** 020 * Constructs a pair. 021 * 022 * @param first The first object. 023 * @param second The second object. 024 */ 025 public Pair(A first, B second) { 026 m_first = first; 027 m_second = second; 028 } 029 030 /** 031 * Returns the first object. 032 * 033 * @return The first object. 034 */ 035 public A getFirst() { 036 return m_first; 037 } 038 039 /** 040 * Returns the second object. 041 * 042 * @return The second object. 043 */ 044 public B getSecond() { 045 return m_second; 046 } 047 048 /** 049 * Returns a pair comprised of the two given objects. 050 * 051 * @param <A> The first object's type. 052 * @param <B> The second object's type. 053 * @param a The first object. 054 * @param b The second object. 055 * @return A pair comprised of the two given objects. 056 */ 057 public static <A, B> Pair<A, B> of(A a, B b) { 058 return new Pair<>(a, b); 059 } 060 061 @Override 062 public String toString() { 063 return String.format("Pair(%s, %s)", m_first, m_second); 064 } 065 066 /** 067 * Checks equality between this Pair and another object. 068 * 069 * @param obj The other object. 070 * @return Whether the two objects are equal or not. 071 */ 072 @Override 073 public boolean equals(Object obj) { 074 return obj == this 075 || obj instanceof Pair<?, ?> other 076 && Objects.equals(m_first, other.getFirst()) 077 && Objects.equals(m_second, other.getSecond()); 078 } 079 080 @Override 081 public int hashCode() { 082 return Objects.hash(m_first, m_second); 083 } 084}