Class Pair<T,U>

java.lang.Object
it.unimi.di.prog2.h23.Pair<T,U>
Type Parameters:
T - the type of the first object.
U - the type of the second object.

public class Pair<T,U> extends Object
A class representing an immutable pair of objects.
  • Field Details

    • first

      private final T first
      The first object of the pair.
    • second

      private final U second
      The second object of the pair.
  • Constructor Details

    • Pair

      public Pair(T first, U second)
      Creates a new pair.
      Parameters:
      first - the first object.
      second - the second object.
      Throws:
      NullPointerException - if first or second is null.
  • Method Details

    • first

      public T first()
      Returns the first object of the pair.
      Returns:
      the first object of the pair.
    • second

      public U second()
      Returns the second object of the pair.
      Returns:
      the second object of the pair.
    • toString

      public String toString()
      Overrides:
      toString in class Object
    • equals

      public boolean equals(Object obj)
      Overrides:
      equals in class Object
    • hashCode

      public int hashCode()
      Overrides:
      hashCode in class Object
    • firstComparator

      public static <T extends Comparable<? super T>> Comparator<Pair<T,?>> firstComparator()
      Returns a comparator that compares pairs by their first element.
      Type Parameters:
      T - the type of the first element.
      Returns:
      a comparator that compares pairs by their first element.
    • secondComparator

      public static <T extends Comparable<? super T>> Comparator<Pair<?,T>> secondComparator()
      Returns a comparator that compares pairs by their second element.
      Type Parameters:
      T - the type of the second element.
      Returns:
      a comparator that compares pairs by their second element.
    • swap

      public static <X, Y> Pair<Y,X> swap(Pair<X,Y> pair)
      Swaps the elements of a pair.
      Type Parameters:
      X - the type of the first element.
      Y - the type of the second element.
      Parameters:
      pair - the pair to swap.
      Returns:
      a new pair with the elements of pair swapped.
      Throws:
      NullPointerException - if pair is null.
    • areEqual

      public static boolean areEqual(Pair<?,?> p1, Pair<?,?> p2)
      Checks if two pairs are equal.
      Parameters:
      p1 - the first pair.
      p2 - the second pair.
      Returns:
      true if p1 and p2 are equal, false otherwise.
      Throws:
      NullPointerException - if p1 or p2 is null.
    • main

      public static void main(String[] args)
      A method to test the class.
      Parameters:
      args - unused.