When the parameter *{mydata.value} is enum then how to transform it into String in thymeleaf?
I want to compare
if:*{mydata.value == "aaa"}
It gives error.
I think it is because I should do something like:
if:*{mydata.value.toString() == "aaa"}.
Try using
if:*{mydata.value.toString().equals("aaa")}
I'm not very familiar with thymeleaf, however that is a common issue in Java. Using '==' will compare the reference to the object, but the .equals() will compare the contents of the string.
If 'mydata.value' is already a string, you can remove the '.toString()'.
If it isn't a string already, you can also use:
if:*{String.valueOf(mydata.value).equals("aaa")}
See more examples of why this happens here
Related
Update:
Using your suggestions in checking between strings, I found out that the difference is on the arrangement of some fields since these strings are actually JSON strings.
Example:
the field username: johndoe#dummy.com on string1 is located at the beginning, but is located somewhere in the middle in string2.
I wonder if there is a way to check or compare 2 json objects regardless of the arrangement of their fields/properties... as long as their contents (field values) are the same.
What I tried:
private boolean sameJsonObject(Object o1, Object o2) throws IOException {
if (o1 == null || o2 == null) {
return false;
}
JsonNode json1 = mapper.readTree(mapper.writeValueAsString(o1));
JsonNode json2 = mapper.readTree(mapper.writeValueAsString(o2));
return json1.equals(json2);
}
this works but I am sure that this can be improved.
Original Problem:
I would like to check if two strings are equal, but these strings are really long that it cannot be set to a variable/string object and would get string constant too long.
I know that there is equals(), equalsIgnoreCase(), and StringUtils.equals(s1, s2) but none of these seems to work.
The strings that I am comparing came from two different sources and comparing it manually get the same results (I mean the contents are the same).
I tried to post the sample strings here but I can't. The size of each string to compare is more than 30k (170k each string).
btw, these strings are actual data (json) and they are really huge and I want to test its equality (content).
Is there a way to do the checking in java?
Thanks!
The simple answer is: compare the two strings char by char.
In other words: most likely, the built-in Java string compare methods are correct, leading to: your input strings aren't equal. It is extremely unlikely that equal strings result in equals() giving false.
Thus the reasonable first option is: change your comparison code so that it:
iterates the first string, char by char
fetches the corresponding char from the second string
compares those (either "full" equals, or ignoring case)
on mismatch: print out the index and the two different chars (where you ensure to print something like "<" + thatChar + ">" just to ensure that non-printable chars, or maybe using Character.getNumericValue())
So, the answer here is basically to enable yourself to do proper debugging.
btw, these strings are actual data (json) and they are really huge and
I want to test its equality (content).
If these are JSON data, don't compare them with String.
Use a JSON library (Jackson, GSON or anything)to represent these data and also to compare them (equals() is generally overridden).It will compare them more cleanly and more specifically by considering or ignoring things like whitespace, node order and so forth...
You can find some examples here.
You could consider more particularly SkyScreamer library that provides multiple flavors to compare JSON. For example this JSONAssert.assertEquals() overload :
public static void assertEquals(org.json.JSONArray expected,
org.json.JSONArray actual,
JSONCompareMode compareMode)
throws org.json.JSONException
where you can specify a JSONCompareMode object such as JSONCompareMode.LENIENT.
170k is not too large for a String, though it is large for a string literal in source code.
Load your two strings from files that contain them, and compare in the normal way using equals.
You mention that the strings are not text but JSON. For most purposes, you'd want to normalize your json (make the whitespace, property order and punctuation the same).
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
my case:
I try to get a value from my MySQL database. This data is defined as a VARCHAR.
This is done in java with a prepared statement and resultset.
String add1 =rs.getString("include");
according to this website table 5.1 states "Can always be converted to these Java types".
therefore a VARCHAR should be able to be converted in a java.lang.string.
When i check the data type in java it indeed gives java.lang.string. So for so good.
My issue is when i try to compare this obtained "String" value to a in java defined String value they don't seem to be equal.
Let's give a simple example.
I get the (VARCHAR) value "1" from the database and store in in String add1
I want to check if this value is indeed "1" and therefore I use the following statement
if(add1=="1")
{
/* do something */
}
Only the values are , according to java, not the same. So I was curious about why this is.
I started searching why those two "Strings" are not equal.
First of I checked the length of both strings. Both came out to be 1 in length as expected.
Afterwards I checked the value of both. To see if both values where indeed the same i wanted to check their hexadecimal representance.
Both came out with the value 0x31. Still as expected.
But then why isn't my if statement accepted by java if both seem to represent the same string-hex-bin-you name it value.
In short: Why is my VARCHAR "String" obtained from a MySQL databse in java not the same as a String defined in java.
Compare values, not memory references:
if(add1.equals("1"))
{
/* do something */
}
Please see this post best answer.
You must always compare strings with the .equals method in your case it will be
add1.equals("1")
"==" or equality operator in Java is a binary operator It is good for compairing primitives like boolean, int, float "==" works fine but when it comes to compare objects it creates confusion with equals method in Java. "==" compare two objects based on memory reference. so "==" operator will return true only if two object reference it is comparing represent exactly same object otherwise "==" will return false.
String comparison is a common scenario of using both == and equals method. Since java.lang.String class override equals method, It return true if two String object contains same content but == will only return true if two references are pointing to same object.
Read more: http://javarevisited.blogspot.com/2012/12/difference-between-equals-method-and-equality-operator-java.html#ixzz3PdLbOre0
You need to compare the Strings with .equals() method. because == checks for object reference.
What is the difference between == vs equals() in Java?
Never thought I will be asking such a trifle query!
Please help with this stack:
if(request.getParameter("cl")=="star"){
txtFilePath = session.getServletContext().getRealPath("/cl.json");
}
else
{ txtFilePath = session.getServletContext().getRealPath("/kl.json");
}
Irrespective of passing cl=star in the url parameters, its not bringing any difference, and showing only kl.json
This code is in jsp, and as of now, no other framework is being used. It's being tested on Tom cat container.
NEVER compare strings using ==.
Always compare using the equals method.
request.getParameter("cl").equals("star")
Note that when using == to compare string objects, you are not comparing it's values but it's references.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
Java String.equals versus ==
I am new to Selenium and Java.
I have tried the below to compare the field value of last name to the one which i supplied.
String lastname=selenium.getValue("//*[#id='lastName']");
System.out.println(lastname);
assertTrue (lastname == "xxx");
It is keep on failing.
Just literally tried to change the last line with help of Eclipse (just trial and error)
assertTrue("lastname.equals("xxx"));
It is working fine... Why it is failed in first case? == is not allowed to compare strings?
Short answer: == checks for same object .equals checks for the same value.
More info in How do I compare strings in Java?
equals function checks the actual contents of the lastname. == operator checks whether the references to the objects are equal.
You must use equals() to compare strings with Java, as you guessed.
You're actually comparing pointers (or really reference equality) when you use == with strings. In other words you're testing if two objects are the same, rather than the content of the objects.
For comparing equality of string ,We Use equals() Method. There are two ways of comparison in java. One is "==" operator and another "equals()" method . "==" compares the reference value of string object whereas equals() method is present in the java.lang.Object class. This method compares content of the string object.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
If statement using == gives unexpected result
Hi I'm using this code to add elements to my ComboBox, and I do not want to add empty elements, here's the code:
public void elrendezesBetoltes(ArrayList<Elrendezes> ElrLista){
int i;
Elrendezes tmp;
model.removeAllElements();
model = new DefaultComboBoxModel(comboBoxItems);
for(i=0; i<ElrLista.size(); i++){
tmp = ElrLista.get(i);
if(tmp.getName()!="")comboBoxItems.add(tmp.getName()); //not working
addButton2(tmp.getSeatnum(),tmp.getCoord(),tmp.getFoglalt());
}
}
My problem is that the if statement is not working, it still adds empty names to my combobox. What am I doing wrong?
Always use equals method to compare Strings: -
if (tmp.getName()!="")
should be: -
if (!tmp.getName().equals(""))
or simply use this, if you want to check for empty string: -
if (!tmp.getName().isEmpty()) {
comboBoxItems.add(tmp.getName());
}
Use equals method to compare string. By using != operator, you are comparing the string instances, which is always going the be true as they(tmp.getName() and "") are not same string instances.
Change
tmp.getName()!=""
to
!"".equals(tmp.getName())
Putting "" as first string in comparison will take care of your null scenario as well i.e. it will not break if tmp.getName() is null.
Use equals():
if (!tmp.getName().equals(""))
Using == or != compares string references, not string contents. This is almost never what you want.
you have to compare Strings with "equals", then it will work
if(!tmp.getName().equals(""))comboBoxItems.add(tmp.getName())
you are comparing for identity (==, !=) but each String instance has its own identity, even when they are equal.
So you need to do !tmp.getName().equals("").
Generally it is considered best practice to start with the constant string first, because it will never be null: !"".equals(tmp.getName())
However, I would recommend to use apache commons lang StringUtils. It has a notEmpty() and notBlank() method that take care of null handling and also trimming.
PS: sometimes identity will work for Strings. but it should not be relied upon as it is caused by compiler or jvm optimization due to String immutability.
Use String#isEmpty()
if(!tmp.getName().isEmpty())
OR:
if(!tmp.getName().equals(""))
Always, check String equality with equals method. == operator only checks if two references point to the same String object.
Another alternative if not on Java 6 and isEmpty is unavailable is this:
if (tmp.getName.length()>0)
Checking for the length is supposed to be quicker than using .equals although tbh the potential gain is so small its not worth worrying too much about.