This question already has answers here:
Comparing boxed Long values 127 and 128
(4 answers)
What's the difference between ".equals" and "=="? [duplicate]
(11 answers)
Closed 7 years ago.
How to compare two long value at runtime. When I got the value of both of long type variable at runtime which same so it should be print else part but the both value is different from each other so it should be print if part.
Long dbData = 54188439.... // Got the value at run time
Long spreadSheet = 54188439.....//Got the value at run time
if(dbData != spreadSheet)
{
Log.i("","Please update your contact");
}
else
{
Log.i("","Not required");
}
Here I always got if part whatever be the condition. Please help me out.
The reason it won't work is because you are comparing the objects, not the values. See also https://stackoverflow.com/a/8968390/4890300 for a great answer.
Make use of equals operator
changed the statement from
if(dbData != spreadSheet)
to
if(!dbData.equals(spreadSheet))
When Same
public static void main(String[] args) {
Long dbData = new Long(54188439);
Long spreadSheet = new Long(54188439);
if (!dbData.equals(spreadSheet)) {
System.out.println("Please update your contact");
} else {
System.out.println("Not required");
}
}
Output
Not required
When Different
public static void main(String[] args) {
Long dbData = new Long(54188439);
Long spreadSheet = new Long(541878439);
if (!dbData.equals(spreadSheet)) {
System.out.println("Please update your contact");
} else {
System.out.println("Not required");
}
}
output
Please update your contact
if(dbData.longValue() != spreadSheet.longValue())
Edit your condition as above. It will compare 2 long values. Your exiting condition compare 2 object references.
Thanks
You should compare two instances of Long-class only with it's equals method, because == operators check the addresses, not the values.
if(!dbData.equals(spreadSheet))
{
Log.i("","Please update your contact");
}
else
{
Log.i("","Not required");
}
Use Long.compare(long x, long y)
if (Long.compare(val1, val2) == 0) {
// values are equal
} else {
// values are not equal
}
Your dbData and spreadSheet are instances of the Long class, not long primitives. You have to compare theme either using the equals() method, or compare their longValue()s. I.e.
if (!dbData.equals(spreadSheet)) {
// ...
} else {
// ...
}
or
if (dbData.longValue() != spreadSheet.longValue()) {
// ...
} else {
// ...
}
You can use below code.
Long dbData = 54188439L;// Got the value at run time
Long spreadSheet = 54188439L;//Got the value at run time
if (!dbData.equals(spreadSheet)) {
}
Related
This question already has answers here:
"Comparison method violates its general contract!"
(13 answers)
Closed 4 years ago.
I know that this kind of question has been asked millions of times if not billions, however I couldn't find my answer yet :)
This compare() method doesn't have Long, Double, Float, ..., it only has Date, boolean, and Null checker, however it shows me that contract violation error, can any one help plz?
Collections.sort(users, new Comparator<MiniUser>() {
#Override
public int compare(MiniUser u1, MiniUser u2) {
boolean resComing = checkMatchConditions(u1,user);
boolean resExists = checkMatchConditions(u2,user);
if(Boolean.valueOf(resComing) && Boolean.valueOf(resExists)) {
if(u1.getLastMatchDate() == null){
return -1;
}else if(u2.getLastMatchDate() ==null ){
return 1;
}else if (u1.getLastMatchDate().toInstant().isBefore(u2.getLastMatchDate().toInstant())){
return -1;
}else {
return 1;
}
}
else if (Boolean.valueOf(resComing)) {
return -1;
}
return 1;
}
});
MiniUser.class
public class MiniUser implements Serializable {
String id;
String name;
Date lastMatchDate;
boolean showCompleteName;
//getters, setters
}
checkMatchConditions return boolean based on some calculations
You should start by reading the JavaDoc of Comparator.compare() to understand what that "contract" is:
The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y,
x)) for all x and y.
In normal terms it says that if "x is greater than y, y must be smaller than x". Sounds obvious, but is not the case in your comparator:
In your case you violate it when two Users have checkMatchConditions false, in which case compare(u1, u2) and compare(u2, u1) both return 1. Hence, there are cases where u1 is greater than u2, and u2 is greater than u1, which is a violation.
Similarely, if both Users have checkMatchConditions true, and their lastMatchDates are both null, they will also violate the contract.
In addition, because you manually try to compare the dates with isBefore, you also return -1 in both cases when two Users have checkMatchConditions true and their lastMatchDates are both equal.
In order to fix this, you should first add a natural language description of how you want the Users to be ordered. Then you can work out the comparator logic.
The error has nothing to do with the Boolean.valueOf() by the way.
Now that you explained how you want to order, have a look at this comparator:
public int compare(MiniUser u1, MiniUser u2)
{
// order by match
boolean u1Matches = checkMatchConditions(u1, user);
boolean u2Matches = checkMatchConditions(u2, user);
if (u1Matches != u2Matches)
{
// put matching ones first
return u1Matches ? -1 : 1;
}
else if (u1Matches)
{
// order by dates
boolean u1HasDate = u1.getLastMatchDate() != null;
boolean u2HasDate = u2.getLastMatchDate() != null;
if (u1HasDate != u2HasDate)
{
// put the ones without date first
return u1HasDate ? 1 : -1;
}
else if (u1HasDate)
{
// order chronologically
return u1.getLastMatchDate().compareTo(u2.getLastMatchDate());
}
else
{
// no dates, no order possible
return 0;
}
}
else
{
// both don't match, no order possible
return 0;
}
}
If I understood your requirements correctly, this should impose a consistent order to your elements. Note how I use Date's compareTo for the date ordering instead of doing it myself, and how I return 0 in case they are "equal" in regards to the order instead of "randomly" returning 1 or -1.
You need to find where sgn(compare(x, y)) == -sgn(compare(y, x)) doesn't hold. I suggest you use brute force to find examples.
Comparator<MiniUser> comp = ...
for (MiniUser a : users) {
for (MiniUser b: users) {
if (a == b) continue;
if (comp.compare(a, b) != -comp.compare(b, a)) {
// print an error message with these two.
}
}
}
This question already has answers here:
How != and == operators work on Integers in Java? [duplicate]
(5 answers)
Closed 5 years ago.
I am trying to write a program which detects "idle" status but I don't see the problem in my code. Could someone help me please with an useful tip? Here's my code:
package idlestatus;
import java.awt.MouseInfo;
public class Idlestatus {
public static void main(String[] args) throws InterruptedException {
Integer firstPointX = MouseInfo.getPointerInfo().getLocation().x;
Integer firstPointY = MouseInfo.getPointerInfo().getLocation().y;
Integer afterPointX;
Integer afterPointY;
while (true) {
Thread.sleep(10000);
afterPointX = MouseInfo.getPointerInfo().getLocation().x;
afterPointY = MouseInfo.getPointerInfo().getLocation().y;
if (firstPointX == afterPointX && firstPointY == afterPointY) {
System.out.println("Idle status");
} else {
System.out.println("(" + firstPointX + ", " + firstPointY + ")");
}
firstPointX = afterPointX;
firstPointY = afterPointY;
}
}
}
If is working but your condition is always getting false, because you are using Integer instead of primitive int. Note that when you use Object, compare them with .equals() method instead of ==.
Therefore :
if (firstPointX.equals(afterPointX) && firstPointY.equals(afterPointY)) {
//your code...
}
See this for difference between == and Object.equals() method.
And as mentioned in comments, you can always use int for such purposes, instead of Integer.
See this for difference between Integer and int.
You are comparing two objects memory addresses , which is Integer object(wrapper class).
if (firstPointX == afterPointX && firstPointY == afterPointY)
What you want to do is compare values in these two objects. To do that you need to use like below:
if (firstPointX.equals(afterPointX) && firstPointY.equals(afterPointY))
Wrapper / covering classes:
There is a wrapper class for each primitive data type.
Primitive types are use for performance reasons(Which better for your
program).
Cannot create objects using primitive types.
Allows a way to create objects and manipulate basic types(i.e.
converting types).
Exsample:
Integer - int
Double - double
If String.length() cannot be used to compare two String objects and determine which object is larger, then what string method would do such a thing? When I run this code it terminates immediately. Is there a method to compare pairs of strings? I'm using the API for the string class as a reference here: https://docs.oracle.com/javase/6/docs/api/java/lang/String.html
public class ThingsComparer {
public static void main(String[] args) {
String ObjectOne = new String("One");
String ObjectTwo = new String("Two");
if (ObjectOne.length() > ObjectTwo.length())
{
System.out.println("ObjectOne is larger");
}
else if (ObjectOne.length() < ObjectTwo.length())
{
System.out.println("ObjectTwo is larger");
}
else if (ObjectOne.equals(ObjectTwo))
{
System.out.println("ObjectOne and ObjectTwo are equal");
}
}
}
.....
.....
else if (ObjectOne.length() == ObjectTwo.length())
{
System.out.println("ObjectOne and ObjectTwo are equal");
}
Furthermore, according to Thilo, you don't need else if (ObjectOne.length() == ObjectTwo.length()) at all specially after you have tried to look for greater and lesser than conditions. What's the 3rd condition? It's equal.
#Peanutcalota
The above code is working fine. The reason that you are not getting any output is that the 2 objects ObjectOne and ObjectTwo are having different strings and have equal lengths.
So the first and second condition will not work as both are having the same length.
The last condition will not work because both strings are different.
ObjectOne.equals(ObjectTwo) will only work if they are having same string.
And I have tried running this program, it is executing fine.
Give it a try.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I wana compare a String with the Key of a Hashmap.
So every time i run this code it uotputs : Not found
I'm new at Java and its surely a little thing but i need help.
Here my code
btnNewButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(!txtSearchHere.getText().isEmpty() && txtSearchHere.getText().length() > 1)
{
String value = txtSearchHere.getText();
txtSearchHere.setText("");
for(Integer key : plzHashMap.keySet())
{
if(key.toString() == value)
{
System.out.println("Matched key = " + value);
}
else
{
System.out.println("Not found");
}
}
}
}
});
For all String-comparisons in Java you should use .equals() instead of ==.
So change:
if(key.toString() == value)
to:
if(key.toString().equals(value))
The reason for this is that == is used for checking if the instances are the exact same (reference), while .equals checks for the same value.
See this SO question (among a lot of others) for more info
Try the following:
String.valueOf(key).equals(value)
And never compare String with ==, use .equals().
Firstly, compare strings using .equals(), not ==.
Secondly, it outputs Not found lots of times because that statement is inside the loop. You can move it outside the loop:
boolean found = false;
for(Integer key : plzHashMap.keySet())
{
if(key.toString().equals(value))
{
System.out.println("Matched key = " + value);
found = true;
break;
}
}
if (!found) {
System.out.println("Not found");
}
However, it would be a lot easier just to convert value to an Integer:
Integer intValue = Integer.parseInt(value);
and then just call get and hasKey - no looping required:
if (plzHashMap.hasKey(intValue)) {
System.out.println("Matched key = " + plzHashMap.get(intValue));
} else {
System.out.println("Not found");
}
Of course, you'd need to handle the case that value can't be parsed to an int.
The == operator checks for reference identity. You should use the equals methods to check for equality:
if(key.toString().equals(value))
But regardless, you're using an O(n) iteration on a hashmap which was designed to provide O(1) key lookup - why not use it?
boolean found = false;
try {
Integer integerValue = Integer.valueOf(value);
if (plzHashMap.containsKey(integerValue)) {
System.out.println("Matched key = " + value)
found = true;
}
} catch (NumberFormatException ignore) {
// value is not even a number
}
if (!found) {
System.out.println("Not found");
}
This question already has answers here:
Hibernate Parameter value [568903] did not match expected type [java.lang.Long]
(3 answers)
Closed 9 years ago.
I have the following code
private Long projectNumber; // with getters and setters
and when I am checking whether projectNumber is null or not, I am getting null pointer exception at the if condition
if(selected.getProjectNumber()!=null){
// do something
}
What could be the reason for this even though Long is a wrapper class.
If I change projectNumber from Long to String, it works fine.
Update 1
private Project selected = new Project();
public Project getSelected() {
return selected;
}
public void setSelected(Project selected) {
this.selected = selected;
}
I am getting selected value in ManagedBean of JSF in the following method
public void onRowSelect(SelectEvent event) {
}
projectNo getters and setters
public Long getProjectNo() {
return projectNo;
}
public void setProjectNo(Long projectNo) {
this.projectNo = projectNo;
}
The problem you have is because selected is null, projectNumber. Change the check to something like:
if(selected != null && selected.getProjectNumber()!=null){
// do something
}
Or alternatively add a separate check for selected above.
If you get an NPE here:
if(selected.getProjectNumber()!=null){
and all getProjectNumber() does is return projectNumber, this strongly indicates that selected is null.
the problem is that selected is null. Check it like:
if(selected != null && selected.getProjectNumber()!=null){
// do something
} else {
// here: selected = null OR projectNumber of selected is null
}
did you check if selected is null
you can do the following
if(null != selected)
{
if(null != selected.getProjectNumber())
{
// do something
}
}
Your object selected is apparently null, try to do:
if ((selected != null) && (selected.getProjectNumber()!=null)){
// do something
}
From what you posted, it sems that the problem is that the object referred by the selected variable is null. You have to check that too:
if(selected !=null && selected.getProjectNumber()!=null){
// do something
}
Explanation: Doing it this way, as the boolean AND (and the OR) operator evaluates only the left condition if it is false, not touching the right side, you won't get a NullPointerExceptyion anymore.
EDIT As OP mentioned that by changing the variable to String the problem is not encountered, as 0xCAFEBABE's suggestion implies, the same error might be possible if the getter returns (or somehow internally uses) a simple long value instead of a Long object, and the value of the variable is null:
/** error getter */
public long getProjectNumber() {
//this would trz to convert null, but what will it convert to? A NullPointerExecption...
return projectNumber;
}