Introduction
The hashCode()
method is called to generate a unique integer value for an object that can be used to identify it. In Java, the hashCode()
method is used to get the hash code of a LocalDate object.
The hashCode()
method is called to generate a unique integer value for an object that can be used to identify it. In Java, the hashCode()
method is used to get the hash code of a LocalDate object.
Create a Java class HashCodeDemo.java
in the ~/project
directory using the following command:
cd ~/project
touch HashCodeDemo.java
Import the LocalDate
class by adding the following code to the HashCodeDemo.java
file:
import java.time.LocalDate;
Create a new object of LocalDate using the of()
method and set the year, month, and day:
LocalDate date = LocalDate.of(2022, 1, 1);
Now, find the hash code of the date object using the hashCode()
method:
int hashCode = date.hashCode();
Add the following code to the main()
method:
public static void main(String[] args) {
LocalDate date = LocalDate.of(2022, 1, 1);
int hashCode = date.hashCode();
System.out.println("Date: " + date);
System.out.println("HashCode: " + hashCode);
}
In the above code, we have printed the date object and the hash code using the println()
method.
Create a new object of LocalDate using the now()
method to get the current date:
LocalDate currentDate = LocalDate.now();
Now, find the hash code of the current date object using the hashCode()
method:
int hashCode = currentDate.hashCode();
Add the following code to the main()
method:
public static void main(String[] args) {
LocalDate currentDate = LocalDate.now();
int hashCode = currentDate.hashCode();
System.out.println("Current Date: " + currentDate);
System.out.println("HashCode: " + hashCode);
}
In the above code, we have printed the current date object and its hash code.
Compile the HashCodeDemo.java
file using the following command:
javac HashCodeDemo.java
Execute the compiled HashCodeDemo
class using the following command:
java HashCodeDemo
After executing the class, examine the output in the terminal. The output of the first code snippet should look like this:
Date: 2022-01-01
HashCode: -1176545808
The output of the second code snippet should look like this:
Current Date: 2022-06-05
HashCode: -2076859288
The hash code is different each time, even for the same date.
In this lab, you have learned how to use the hashCode()
method with the LocalDate class in Java. By using the hashCode()
method, we can get a unique integer value that can be used to identify a date object. We have created two date objects, one with a specific date and the other with the current date, and then found the hash code of both objects using the hashCode()
method. Finally, we have compiled and executed the Java code in the terminal.