Comparing two objects with Objects.equals in Java7

Comparing two objects with Objects.equals in Java7

You can use the Objects class from Java 7.

Objects.equals(a,b) compares a and b.

It returns true if they are the same, false if they are different.

This method is very useful because it allows comparison without worrying about null.

In the past, you would have compared them as follows

String a = "1";
if (a != null && a.equals(b)) {
  // 処理

Or you would have taken the constant first and compared it with equals.

With Objects.equals, you can compare without considering nulls.

package jp.confrage;

import java.math.BigDecimal;
import java.util.Objects;

public class Test1{
  public static void main(String[] args) {
    BigDecimal bd1 = new BigDecimal("10");
    BigDecimal bd2 = new BigDecimal("10");
    String a = "1";
    String b = "1";
    System.out.println(Objects.equals(null, null));
    System.out.println(Objects.equals(a, b));
    System.out.println(Objects.equals(bd1, bd2));

The results are as follows


Objects.equals also takes the type into account.

String a = "1";
BigDecimal b = BigDecimal.ONE;
Objects.equals(a,b);// → false


Discover more from 株式会社CONFRAGE ITソリューション事業部

Subscribe now to keep reading and get access to the full archive.

Continue reading

Copied title and URL