Home > database >  How to avoid null excpetion when using equals()method in java
How to avoid null excpetion when using equals()method in java

Time:09-27

I was trying to compare the name of two different Objects, but I kept getting exceptions when using the equals() method to compare an item to null. I've tried so many ways, including other.equals(haha), haha.equals(other), etc, but all failed.


public final class ItemImpl implements Item {
  private final String name;

  public ItemImpl(String name) {
    if (name == null) {
      throw new IllegalArgumentException("name cannot be null!");
    }
    this.name = name;
  }

  @Override
  public String getName() {
    return this.name;
  }

  public boolean equals(Object other) {
    Object haha = name;

    return other.toString().equals(haha.toString());
  }

  public String toString() {
    return this.name;
  }
}

CodePudding user response:

Call Objects.equals for tolerance of nulls.

Objects.equals(a,b);
does the job for you, in your case you have also to look that the toString method which you call is not on a null reference.
So use:
return other != null && Objects.equals(toString(), other.toString());

CodePudding user response:

String one = null;
String two = null;
int res = org.apache.commons.lang3.StringUtils.compare(one, two);
  •  Tags:  
  • java
  • Related