What is Objects.deepEquals in java?

Overview

The deepEquals method of the Objects class in Java is a static method used to check whether two given objects are deep equals.

  1. Two null values are always deeply equal.
  2. If both the objects passed are arrays, then Arrays.deepEquals is used to check equality.
  3. Otherwise the equality is determined by using the equals method of the first argument.

Syntax

public static boolean deepEquals(Object a, Object b)

Parameters

  • Object a: First object
  • Object b: Object to be checked for deep equality

Return value

The method returns true if the objects are deeply equal. Otherwise it returns false.

Example

In the code below, we pass the null value to both parameters of the method. If we run the program, it should print true.

import java.util.Objects;
public class Main {
public static void main(String[] args) {
Object a = null;
Object b = null;
System.out.println(Objects.deepEquals(a, b));
}
}

In the code below, we pass 2 arrays. As the contents of the array are different, the program below prints false.

import java.util.Objects;
public class Main {
public static void main(String[] args) {
int[] a = new int[3];
a[0] = 1;
a[1] = 2;
a[2] = 3;
int[] b = new int[3];
b[0] = 1;
b[1] = 5;
b[2] = 3;
System.out.println(Objects.deepEquals(a, b));
}
}

In the code below, the Student class is defined. We pass two Student objects that have the same name and id values. The equals method of the Student class is called to determine the equality of the two objects.

import java.util.Objects;
public class Main {
static class Student{
public String name;
public int id;
public Student(String name, int id) {
this.name = name;
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return id == student.id && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, id);
}
}
public static void main(String[] args) {
Student s1 = new Student("bob", 123);
Student s2 = new Student("bob", 123);
System.out.println(Objects.deepEquals(s1, s2));
}
}

Free Resources