The title is pretty self-explanatory. I'm moving from C# to Java. I have an object and a getter method which returns its ID. I want to compare the ids of two objects of the same type and check if the values of their ids are equal.
tried:
obj.getId() == obj1.getId();
Long id1 = obj.getId();
Long id2 = obj1.getId();
assertTrue(id1.equals(id2))
assertTrue(id1== id2)
equals() is a built-in function in java that compares this object to the specified object. The result is true if and only if the argument is not null and is a Long object that contains the same long value as this object. It returns false if both the objects are not same.
Primitives. Like in other languages, we can compare the values of primitives with the < , > , <= , and >= operator. The same problems of floating-point data types apply to them, so be aware. Also, boolean isn't comparable except for equality with == and !=
The java. lang. Long. compareTo() method compares two Long objects numerically.
To compare two primitive long you can simply use ==
Example:
long x = 1L;
long y = 1L;
if (x == y) {
System.out.println("value of x and y are same");
}
To compare two Long objects you can use Long.compare(long x, long y). This method was added in java 1.7. Below is the method implementation:
public static int compare(long x, long y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
Example:
Long x = new Long(1);
Long y = new Long(1);
if (Long.compare(x,y) == 0) {
System.out.println(values of x and y are same);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With