Since Java 7 you can use the static method java.util.Objects.equals(Object, Object) to perform equals checks on two objects without caring about them being null.
If both objects are null, it will return true, if one is null and the other isn't, it will return false. Otherwise, it will return the result of calling equals on the first object with the second as argument.
Since Java 7 you can use the static method java.util.Objects.equals(Object, Object) to perform equals checks on two objects without caring about them being null.
If both objects are null, it will return true, if one is null and the other isn't, it will return false. Otherwise, it will return the result of calling equals on the first object with the second as argument.
This is what Java internal code uses (on other compare methods):
public static boolean compare(String str1, String str2) {
return (str1 == null ? str2 == null : str1.equals(str2));
}
Videos
You're not comparing the objects themselves, you're comparing their references.
Try
c != null
in your if statement.
!c.equals(null)
That line is calling the equals method on c, and if c is null then you'll get that error because you can't call any methods on null. Instead you should be using
c != null
I've already discovered that comparing a generic type requires you to use an int to restore the value of compareTo, but if I'm trying to check if T value == Null, java throws an error stating that the compareTo (null) method is undefined for type T.
the code I have so far is
int cmp; if(cmp = tree.get(index).compareTo(null) == 0)
to check if the value at the index of tree == null.
Thanks in advance :)
edit: well, I actually just fixed it by deleting cmp XD
When I type
string1 == string2
IntelliJ tells me to switch to equals(), which it says is null-safe.
But is == operator not null-safe?
I tried null == "abc", "abc" == null, null == null, but they consistently gave me right false false true.
What am I missing here?
Java 7.0 added a new handy class: Objects.
It has a method exactly for this: Objects.equals(Object a, Object b)
Apache Commons Lang has such a method: ObjectUtils.equals(object1, object2). You don't want generics on such a method, it will lead to bogus compilation errors, at least in general use. Equals knows very well (or should - it is part of the contract) to check the class of the object and return false, so it doesn't need any additional type safety.
You can simply use Apache Commons Lang:
result = ObjectUtils.compare(firstComparable, secondComparable)
Using Java 8:
private static Comparator<String> nullSafeStringComparator = Comparator
.nullsFirst(String::compareToIgnoreCase);
private static Comparator<Metadata> metadataComparator = Comparator
.comparing(Metadata::getName, nullSafeStringComparator)
.thenComparing(Metadata::getValue, nullSafeStringComparator);
public int compareTo(Metadata that) {
return metadataComparator.compare(this, that);
}
If Java 7+, use Objects.equals(); its documentation explicitly specifies that:
[...] if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals method of the first argument.
which is what you want.
If you don't, your method can be rewritten to:
return s1 == null ? s2 == null : s1.equals(s2);
This works because the .equals() contract guarantees that for any object o, o.equals(null) is always false.
From Objects.equals():
return (a == b) || (a != null && a.equals(b));
Very simple, self-explaining and elegant.
The == operator tests whether two variables have identical value. For object references, this means that the variables must refer to the same object (or both variables must be null). The equals() method, of course, requires that the variable on which it is invoked not be null. It's behavior depends on the type of object being referenced (on the actual object, not on the declared type). The default behavior (defined by Object) is to simply use ==.
To get the behavior you want, you can do:
System.out.println(a == null ? b == null : a.equals(b));
NOTE: as of Java 7, you can use:
System.out.println(java.util.Objects.equals(a, b));
which does the same thing internally.
a.equals(b) returns a NullPointerException because it's literally
null.equals(...)
and null doesn't have a .equals (or any other method).
same thing with b.equals(a)
a == b returns true because it's null == null (obviously true). So to compare you have to check a and b for null or something like...
if (a != null)
return a.equals(b); // This works because a is not null. `a.equals(null)` is valid.
else if (b != null)
return b.equals(a); // a is null, but b is not
else
return a == b;
the ?: operator is a bit more concise for this
There is new utility class available in jdk since 1.7 that is Objects .
This class consists of static utility methods for operating on objects. These utilities include null-safe or null-tolerant methods for computing the hash code of an object, returning a string for an object, and comparing two objects.
You can use Objects.equals, it handles null.
Objects.equals(Object a, Object b) Returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals method of the first argument.
if(Objects.equals(myString,myString2)){...}
You can use Apache object utils
ObjectUtils.equals(Object object1, Object object2) -- Returns boolean
this method has been replaced by java.util.Objects.equals(Object, Object) in Java 7
The method you linked to takes in two objects and is a static method. You need to call it like Objects.equals(a, b). Instead you are calling .equals() on a null object which throws NPE
Shouldn't it return true since they are both null?
nop. since a is a null-referenced object, invoking ANY instance method on that object will throw a NPE
so what you can do:
if you are still on java 6 do
System.out.println(a == null ? b == null : a.equals(b));
and since java 7
System.out.println(Objects.equals(a, b));
They're two completely different things. == compares the object reference, if any, contained by a variable. .equals() checks to see if two objects are equal according to their contract for what equality means. It's entirely possible for two distinct object instances to be "equal" according to their contract. And then there's the minor detail that since equals is a method, if you try to invoke it on a null reference, you'll get a NullPointerException.
For instance:
class Foo {
private int data;
Foo(int d) {
this.data = d;
}
@Override
public boolean equals(Object other) {
if (other == null || other.getClass() != this.getClass()) {
return false;
}
return ((Foo)other).data == this.data;
}
/* In a real class, you'd override `hashCode` here as well */
}
Foo f1 = new Foo(5);
Foo f2 = new Foo(5);
System.out.println(f1 == f2);
// outputs false, they're distinct object instances
System.out.println(f1.equals(f2));
// outputs true, they're "equal" according to their definition
Foo f3 = null;
System.out.println(f3 == null);
// outputs true, `f3` doesn't have any object reference assigned to it
System.out.println(f3.equals(null));
// Throws a NullPointerException, you can't dereference `f3`, it doesn't refer to anything
System.out.println(f1.equals(f3));
// Outputs false, since `f1` is a valid instance but `f3` is null,
// so one of the first checks inside the `Foo#equals` method will
// disallow the equality because it sees that `other` == null
In addition to the accepted answer (https://stackoverflow.com/a/4501084/6276704):
Since Java 1.7, if you want to compare two Objects which might be null, I recommend this function:
Objects.equals(onePossibleNull, twoPossibleNull)
java.util.Objects
This class consists of static utility methods for operating on objects. These utilities include null-safe or null-tolerant methods for computing the hash code of an object, returning a string for an object, and comparing two objects.
Since: 1.7