Java's Pair Class

Java's Pair Class

Java's standard Pair class has nothing to do with Map or hashing. In fact, it is not even in the Java Collections Framework. But we introduce it here because it is often confused with Java's Map class. The Pair class can be found in javafx.util (not java.util).

Java's Pair class is useful when we want to:

  • return two items from a method, instead of one
  • avoid using a parallel array
  • associate two items with one another that typically do not have a functional relationship between them




Using Java's Pair Class to Increase Scalability

Using parallel arrays is a great approach for beginners. But when the size of the data set starts to grow, parallel arrays can be a dangerous architecture to use.



When to Use Java's Map Class versus Java's Pair Class

Is it a function? That is typically the question a programmer needs to ask before deciding between the Map and Pair Classes in Java. In a Map, they Key values must be unique. So the <Key, Value> relationship represents a function. But with Pair objects, there is no relationship between the two. Consider, for example, if we had an application that needed to store the <x,y> information for a scatterplot such as this:

scatterplot
 Which would be the right data structure to use? Clearly both X and Y values are repeated as the above is not a function. Thus, Pair would be the appropriate data structure, not Map.

Why Does the Pair Class Have a Hash Value

The built-in hashCode() method in the Pair class is useful because it can be used to tell quickly if two Pair objects are equal by comparing their hash values. It can also be useful if a user wants to place Pair objects in a custom hash table. Whereas a HashMap hashes a Key to reference a Value, Java's Pair class generates a unique hash value to identify a Key-Value pair.

Oracle Documentation for the Pair Class

Type Method Description

boolean equals(Object o) Test this Pair for equality with another Object.

K getKey() Gets the key for this pair.

V getValue() Gets the value for this pair.

int hashCode() Generate a hash code for this Pair.

String toString() String representation of this Pair.

Other Examples of Java Pairs