Ordered pair in Java
In Java, an ordered pair is a simple data structure that stores two values in a certain order. Unlike several other programming languages, Java does not include a built-in class named "OrderedPair". Alternatively, you can make your own ordered pair implementation with arrays, lists, or custom classes.
Pair Class
The Pair class is not included in the standard Java library, although it can be found in a number of third-party libraries, including Apache Commons Lang and JavaFX. This class is used to store a pair of two values, usually of different types, and it has methods for accessing and manipulating these values as a whole.
The Pair class from the javafx.util package in JavaFX is one of the most often used implementations. This class allows you to build a pair of values of the provided types. Each pair is made up of a "key" and a "value" (sometimes known as the first and second components), and the Pair class provides methods for accessing and modifying these elements.
Characteristics of Pair Class
- Immutable
Instances of the Pair class are often immutable, meaning once created, their values cannot be modified. This immutability ensures thread safety and prevents unintended changes to the pair's content.
- Encapsulation
The Pair class encapsulates two related values into a single object, enhancing code readability and organization by grouping related data.
- Convenient Accessors
Methods like getKey() and getValue() provide easy access to the key and value components of the pair, respectively. Some implementations might also offer methods for modifying or creating new pairs.
- Limited Semantic Meaning
While useful for general-purpose use cases, Pair objects might lack semantic meaning compared to custom classes with descriptive field names. This can sometimes lead to less readable code, especially when dealing with complex data structures.
- Library Dependencies
Depending on the implementation, using the Pair class might introduce dependencies on external libraries, such as JavaFX or Apache Commons. This should be considered when choosing to use Pair in your project.
Note: To run these programs
Download and Install JavaFX: Download the JavaFX SDK from the official website and install it on your system.
Configure Your IDE: If you're using an Integrated Development Environment (IDE) like IntelliJ IDEA or Eclipse, configure it to recognize JavaFX and include the necessary libraries in your project's build path.
Set Up Module Path: When compiling and running JavaFX applications, you need to specify the module path to include the JavaFX modules. This can be done using command-line options or through your IDE's project settings.
Include JavaFX Libraries: Make sure to include the JavaFX libraries in your project's dependencies. This typically involves adding the javafx-sdk/lib directory to your classpath.
Methods of Pair Class
- getKey()
The getKey() method is used to retrieve the key (first element) of an ordered pair. When working with pairs, especially instances of Pair class from libraries like JavaFX or Apache Commons, this method provides a convenient way to access the first element of the pair.
Filename: OrderedPairDemo.java
import javafx.util.Pair;
public class OrderedPairDemo {
public static void main(String[] args) {
// Creating an ordered pair with String key and Integer value
Pair<String, Integer> orderedPair = new Pair<>("Apple", 10);
// Accessing the key of the ordered pair using getKey() method
String key = orderedPair.getKey();
// Displaying the key
System.out.println("Key: " + key);
}
}
Output:
Key: Apple
In this example, we import the Pair class from the javafx.util package to use it in our code. We create an ordered pair where the key is of type String and the value is of type Integer. We initialize it with the key "Apple" and the value 10.
We then use the getKey() method to retrieve the key of the ordered pair and store it in a variable named key. Finally, we print out the key to the console. The getKey() method retrieves the key (first element) of the ordered pair. In this case, it will return "Apple".
- getValue()
The getValue() method is a crucial method provided by the Pair class in Java, particularly from the javafx.util package. It allows you to retrieve the value (second element) of an ordered pair. This method is essential when you need to access the value associated with a specific key in a pair.
Filename: OrderedPairDemo1.java
import javafx.util.Pair;
public class OrderedPairDemo1 {
public static void main(String[] args) {
// Creating an ordered pair with String key and Integer value
Pair<String, Integer> orderedPair = new Pair<>("Apple", 10);
// Accessing the value of the ordered pair using getValue() method
Integer value = orderedPair.getValue();
// Displaying the value
System.out.println("Value: " + value);
}
}
Output:
Value: 10
In this example, we import the Pair class from the javafx.util package to use it in our code. We create an ordered pair where the key is of type String and the value is of type Integer. We initialize it with the key "Apple" and the value 10.
We then use the getValue() method to retrieve the value of the ordered pair and store it in a variable named value. Finally, we print out the value to the console. The getValue() method retrieves the value (second element) of the ordered pair. In this case, it will return 10.
- Pair(K key, V value)
The Pair(K key, V value) constructor is used to create a new pair with the specified key and value. This constructor is particularly useful when you want to associate two values together in a single object, forming a key-value pair.
Filename: PairCreationDemo.java
import javafx.util.Pair;
public class PairCreationDemo {
public static void main(String[] args) {
// Creating a new pair with a String key and an Integer value
Pair<String, Integer> pair = new Pair<>("Apple", 10);
// Displaying the details of the created pair
System.out.println("Created Pair:");
System.out.println("Key: " + pair.getKey()); // Accessing and printing the key
System.out.println("Value: " + pair.getValue()); // Accessing and printing the value
System.out.println("Pair: " + pair); // Printing the pair directly
}
}
Output:
Created Pair:
Key: Apple
Value: 10
Pair: (Apple, 10)
In this example, we create a Pair object named pair with the key "Apple" and the value 10 and then display the details of the pair: We print the key using pair.getKey(), which returns "Apple".
We print the value using pair.getValue(), which returns 10. We print the pair object directly, which invokes its toString() method and displays the key-value pair as (Apple, 10).
- equals(Object obj)
The equals(Object obj) method is a fundamental method in Java that determines whether two objects are equal. When overridden, it allows you to define custom equality comparison logic for your class. In the case of the Pair class, the equals method is often overridden to compare the keys and values of two pairs for equality.
Filename: PairEqualsDemo.java
import javafx.util.Pair;
import java.util.Objects;
public class PairEqualsDemo {
public static void main(String[] args) {
// Creating two pairs with the same key-value pairs
Pair<String, Integer> pair1 = new Pair<>("Apple", 10);
Pair<String, Integer> pair2 = new Pair<>("Apple", 10);
// Creating another pair with different key-value pairs
Pair<String, Integer> pair3 = new Pair<>("Banana", 20);
// Testing equality of pair1 and pair2
System.out.println("pair1.equals(pair2): " + pair1.equals(pair2)); // Output: true
// Testing equality of pair1 and pair3
System.out.println("pair1.equals(pair3): " + pair1.equals(pair3)); // Output: false
}
static class Pair<K, V> {
private final K key;
private final V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Pair<?, ?> other = (Pair<?, ?>) obj;
return Objects.equals(getKey(), other.getKey()) &&
Objects.equals(getValue(), other.getValue());
}
@Override
public int hashCode() {
return Objects.hash(key, value);
}
}
}
Output:
pair1.equals(pair2): true
pair1.equals(pair3): false
The Pair class represents a key-value pair and contains a constructor to initialize the key and value, as well as methods to access them (getKey() and getValue()). The equals method is overridden to compare the keys and values of two pairs for equality. If the keys and values are equal, the method returns true; otherwise, it returns false.
The hashCode method is overridden to ensure consistency with the equals method, necessary for collections like HashMap or HashSet. Two pairs (pair1 and pair2) with the same key-value pairs are created, and their equality is tested, returning true. Another pair (pair3) with different key-value pairs is created, and its equality with pair1 is tested, returning false.
- hashCode()
The hashCode() method in Java generates a hash code for an object. In the context of the Pair class, it's typically overridden to ensure consistency with the equals method when the class is used in collections like HashMap or HashSet. This ensures that equal objects have the same hash code.
Filename: PairHashCodeDemo.java
import javafx.util.Pair;
import java.util.Objects;
public class PairHashCodeDemo {
public static void main(String[] args) {
// Creating a pair with a String key and an Integer value
Pair<String, Integer> pair = new Pair<>("Apple", 10);
// Getting the hash code of the pair
int hashCode = pair.hashCode();
// Displaying the hash code
System.out.println("Hash code of the pair: " + hashCode);
}
static class Pair<K, V> {
private final K key;
private final V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Pair<?, ?> other = (Pair<?, ?>) obj;
return Objects.equals(getKey(), other.getKey()) &&
Objects.equals(getValue(), other.getValue());
}
@Override
public int hashCode() {
return Objects.hash(key, value);
}
}
}
Output:
Hash code of the pair: <hash code value>
The <hash code value> will be the generated hash code of the Pair object based on its key and value.
We override the hashCode method to generate a hash code based on the key and value of the pair. This ensures consistency with the equals method and is necessary when our class is used in collections such as HashMap or HashSet. We create a pair (pair) with a key of type String ("Apple") and a value of type Integer (10). We then retrieve the hash code of the pair using the hashCode() method.
- toString()
The toString() method in Java returns a string representation of an object. When overridden, it allows you to define how an object should be represented as a string. In the context of the Pair class, the toString() method is often overridden to provide a string representation that includes the key-value pair.
Filename: PairToStringDemo.java
import javafx.util.Pair;
public class PairToStringDemo {
public static void main(String[] args) {
// Creating a pair with a String key and an Integer value
Pair<String, Integer> pair = new Pair<>("Apple", 10);
// Getting the string representation of the pair
String pairString = pair.toString();
// Displaying the string representation
System.out.println("String representation of the pair: " + pairString);
}
}
Output:
String representation of the pair: (Apple, 10)
We create a Pair object with a key of type String ("Apple") and a value of type Integer (10), calls the toString() method on the Pair object pair, which returns a string representation of the pair. Displaying the String Representation: Finally, we print the string representation of the pair to the console.
Complete implementation using all methods in a single code
Filename: PairDemo.java
import javafx.util.Pair;
import java.util.Objects;
public class PairDemo {
public static void main(String[] args) {
// Creating a pair with a String key and an Integer value
Pair<String, Integer> pair1 = new Pair<>("Apple", 10);
Pair<String, Integer> pair2 = new Pair<>("Orange", 20);
Pair<String, Integer> pair3 = new Pair<>("Apple", 10);
// Using getKey() method to get the key of pair1
String key = pair1.getKey();
System.out.println("Key of pair1: " + key);
// Using getValue() method to get the value of pair1
Integer value = pair1.getValue();
System.out.println("Value of pair1: " + value);
// Using equals() method to compare pair1 and pair2
boolean isEqual = pair1.equals(pair2);
System.out.println("pair1 equals pair2: " + isEqual);
// Using equals() method to compare pair1 and pair3
isEqual = pair1.equals(pair3);
System.out.println("pair1 equals pair3: " + isEqual);
// Using hashCode() method to get the hash code of pair1
int hashCode = pair1.hashCode();
System.out.println("Hash code of pair1: " + hashCode);
// Using toString() method to get the string representation of pair1
String pairString = pair1.toString();
System.out.println("String representation of pair1: " + pairString);
}
}
Output:
Key of pair1: Apple
Value of pair1: 10
pair1 equals pair2: false
pair1 equals pair3: true
Hash code of pair1: <hash code value>
String representation of pair1: (Apple, 10)
The output of the provided code will vary based on the specific keys and values used to create the pairs. However, it will demonstrate the usage of various methods provided by the Pair class, including getKey(), getValue(), equals(), hashCode(), and toString().