In Java, a Pair
class is often used to represent a simple container for two objects (often referred to as a “tuple” in other languages). The Pair
class is not a built-in part of Java’s standard library (prior to Java 8), but it can be easily implemented.
You might also come across Pair
in various Java libraries, such as Apache Commons Lang, which has a Pair
class.
Here’s an example of a simple Pair
class in Java:
Custom Pair
Class:
public class Pair<T, U> {
private T first;
private U second;
// Constructor to initialize the Pair
public Pair(T first, U second) {
this.first = first;
this.second = second;
}
// Getter for the first element
public T getFirst() {
return first;
}
// Getter for the second element
public U getSecond() {
return second;
}
// Setter for the first element
public void setFirst(T first) {
this.first = first;
}
// Setter for the second element
public void setSecond(U second) {
this.second = second;
}
// Override toString for better readability
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
// Override equals and hashCode if necessary (for comparing pairs)
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) obj;
return first.equals(pair.first) && second.equals(pair.second);
}
@Override
public int hashCode() {
return 31 * first.hashCode() + second.hashCode();
}
}
Usage of the Pair
class:
public class Main {
public static void main(String[] args) {
// Creating a pair of Integer and String
Pair<Integer, String> pair = new Pair<>(1, "Java");
// Accessing the elements of the pair
System.out.println("First: " + pair.getFirst());
System.out.println("Second: " + pair.getSecond());
// Modifying the elements
pair.setFirst(2);
pair.setSecond("Python");
System.out.println("Updated Pair: " + pair);
}
}
Output:
First: 1
Second: Java
Updated Pair: (2, Python)
Java Libraries with Pair
:
If you want to avoid writing your own Pair
class, libraries like Apache Commons Lang and JavaFX provide implementations:
- Apache Commons Lang:
org.apache.commons.lang3.tuple.Pair
- JavaFX:
javafx.util.Pair
For example, using Apache Commons Lang’s Pair
:
import org.apache.commons.lang3.tuple.Pair;
public class Main {
public static void main(String[] args) {
Pair<Integer, String> pair = Pair.of(1, "Java");
System.out.println("First: " + pair.getLeft());
System.out.println("Second: " + pair.getRight());
}
}