This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 1 year ago.
When the code is 20, nonSmoking should be 1, but always returns null. After debugging I saw that it always returns null
How to set a variable nonSmoking correctly?
public static String mapSmokingAmenities(ContentFragmentList list){
SolrContentFragment solrFragments = list.getFragment(SolrContentFragment.class);
List<String> ausstattungPositions = solrFragments.getAusstattungPosition();
String nonSmoking = new String();
for(String code : ausstattungPositions){
if(code == "20" || code == "36"){
nonSmoking = "1";
}
if(code == "51"){
nonSmoking ="0";
}
}
return nonSmoking;
}
Comparing objects using == compares the address. You can find out if a object points to the same instance you want to work with. Only primitive datatypes (int/...) can be compared with value like that.
For Strings as being object please use equals() method for the value compare.
If you have custom DTO/POJO where you want to compare value and not reference you need to overwrite the hashCode and equals method there.
Probably this could help
public static String mapSmokingAmenities(ContentFragmentList list){
SolrContentFragment solrFragments = list.getFragment(SolrContentFragment.class);
List<String> ausstattungPositions = solrFragments.getAusstattungPosition();
String nonSmoking = "";
for(String code : ausstattungPositions){
switch(code) {
case "20":
case "36":
nonSmoking = "1";
break;
case "51":
nonSmoking = "0";
break;
default:
// do nothing
break;
}
}
return nonSmoking;
}
You should use an enum for your codes and your result. Be aware, that you set nonSmoking every time being code 20, 36 or 51. Probably you should break your for loop. Don't create a new String but use an empty String "".
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
Replace will create new object and both side this new will be compared. then why it showing false.
When exactly created new string will be added in string pool?
if("String".replace("g", "G") == "String".replace("g", "G"))
{
System.out.println("True");
} else {
System.out.println("False");
}
because replace() will always return a new String instance. So the 2 same calls to replace method will return 2 different instances with same value.
use equals() instead of == if you want to compare value
Use intern() on both replaced values if you want to add the string to the string constants pool (and are bent on using == :P)
if ("String".replace("g", "G").intern() == "String".replace("g", "G").intern()) {
System.out.println("True");
} else {
System.out.println("False");
}
}
OP :
true
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm writing some codes that test if there is "xx" in a string. For instance, doubleX("aaxxbb") should return true, and doubleX("axabb") should return false.
Here is my code:
private static boolean doubleX(String str) {
for(int i=0;i<str.length()-1;i++){
System.out.println(str.substring(i,i+2));
if(str.substring(i,i+2) == "xx") return true;
}
return false;
}
Why does doubleX("aaxxbb") return false?
You have to use .equals instead of ==. For more information, follow the duplication message.
return str.contains("xx");
Is a lot clearer though.
You should understand the difference between == and equals: the first one compares references, the second compares actual values.
Your code is wildly inefficient.
I'd try something like this:
private static boolean doubleX(String str) {
return (str.indexOf("xx") != -1);
}
Use equals() for checking the content of a String to another rather than ==. == checks for reference equality.
private static boolean doubleX(String str) {
for(int i=0;i<str.length()-1;i++){
System.out.println(str.substring(i,i+2));
if(str.substring(i,i+2).equals("xx")) return true;
}
return false;
}
Even you can directly code like:
private static boolean doubleX(String str) {
return str.contains("xx");
}
I'm trying to figure out how to create a method to find a string inside an array and print that string out along with its index. I think the method signature is correct but I can't figure out how to return the string value in the method.
String name = search(array,"Dog"); //the method implementation in main
System.out.println(name);
.
public static int search(String[] array, String key)
{
for (int i= 0; i< array.length; i++)
{
if ( array[i] == key )
return i;
}
return ("Name cannot be found in array);
}
You can't return a String from a method that is declared to return int. The most common ways to indicate failure are to return an out-of-range value:
return -1;
Or to throw an exception:
throw new NameNotFoundException("Name cannot be found in array");
Also, this line won't work:
if ( array[i] == key )
Strings need to be compared with equals(), not ==. The == operator checks that the strings are the same objects, not that their contents are identical.
if (key == null && array[i] == null ||
key != null && key.equals(array[i]))
And make sure that you don't call .equals() on a null reference. The above code checks for this possibility.
Why do you want to return the String? Whoever calls this method already knows what the String is, because they had to provide it in the first place. (Otherwise how would know what you were looking for :P)
also you should be doing array[i].equals(key).
== is for object equality.
.equals() is for value equality.
If you want to return a String, then...your return type should be String, not int.
Also, you shouldn't use == with Strings, or with most objects, use array[i].equals(key) instead.
The biggest question is why implement search when java has already implemented it for you?
String[] array;
String val = "Dog";
if( Arrays.asList(array).contains(val) ){
System.out.println("your string is found");
} else {
System.out.println("your string is found");
}
Or better yet true to you implementation
String[] array;
String val = "Dog";
String name = ( Arrays.asList(array).contains(val) ) ? val : "Name cannot be found in array";
it should be noted that Arrays.asList DOES NOT COPY the array merely wraps it in a List structure so that it can be treated as a enumerable. The performance of this method is roughly the same as the one your provided.
You allready have String value that you are searching. Why you need to return that ?
Just return index
int index = search(array,"Dog");
First fix your comparison to use the equals method as:
if (array[i].equals(key))
Also change last return statement as:
return -1; //string not found
Then simply do this (use array[searchIndex] to get the string):
int searchIndex = search(array,"Dog");
if(i >= 0){
System.out.println("String="+array[searchIndex] + ", Array Index="+searchIndex);
}else{
System.out.println("String not found");
}
you can try this one .............
import java.util.*;
public class xyz {
public static void main(String [] args){
String [] sa = {"abc","def","ghi"};
Arrays.asList(sa);
Arrays.sort(sa);
for(String s : sa){
System.out.println(s);
}
}
}
I want to compare two strings for equality when either or both can be null.
So, I can't simply call .equals() as it can contain null values.
The code I have tried so far :
boolean compare(String str1, String str2) {
return ((str1 == str2) || (str1 != null && str1.equals(str2)));
}
What will be the best way to check for all possible values including null ?
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 another 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));
}
For these cases it would be better to use Apache Commons StringUtils#equals, it already handles null strings. Code sample:
public boolean compare(String s1, String s2) {
return StringUtils.equals(s1, s2);
}
If you dont want to add the library, just copy the source code of the StringUtils#equals method and apply it when you need it.
For those on android, who can't use API 19's Objects.equals(str1, str2), there is this:
android.text.TextUtils.equals(str1, str2);
It is null safe. It rarely has to use the more expensive string.equals() method because identical strings on android almost always compare true with the "==" operand thanks to Android's String Pooling, and length checks are a fast way to filter out most mismatches.
Source Code:
/**
* Returns true if a and b are equal, including if they are both null.
* <p><i>Note: In platform versions 1.1 and earlier, this method only worked well if
* both the arguments were instances of String.</i></p>
* #param a first CharSequence to check
* #param b second CharSequence to check
* #return true if a and b are equal
*/
public static boolean equals(CharSequence a, CharSequence b) {
if (a == b) return true;
int length;
if (a != null && b != null && (length = a.length()) == b.length()) {
if (a instanceof String && b instanceof String) {
return a.equals(b);
} else {
for (int i = 0; i < length; i++) {
if (a.charAt(i) != b.charAt(i)) return false;
}
return true;
}
}
return false;
}
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);
}
Or you can also use the below method using Java
public static boolean compare(String first, String second) {
return(Objects.isNull(first) ? Objects.isNull(second) :
first.equals(second));
}
Since version 3.5 Apache Commons StringUtils has the following methods:
static int compare(String str1, String str2)
static int compare(String str1, String str2, boolean nullIsLess)
static int compareIgnoreCase(String str1, String str2)
static int compareIgnoreCase(String str1, String str2, boolean nullIsLess)
These provide null safe String comparison.
Compare two string using equals(-,-) and equalsIgnoreCase(-,-) method of Apache Commons StringUtils class.
StringUtils.equals(-, -) :
StringUtils.equals(null, null) = true
StringUtils.equals(null, "abc") = false
StringUtils.equals("abc", null) = false
StringUtils.equals("abc", "abc") = true
StringUtils.equals("abc", "ABC") = false
StringUtils.equalsIgnoreCase(-, -) :
StringUtils.equalsIgnoreCase(null, null) = true
StringUtils.equalsIgnoreCase(null, "abc") = false
StringUtils.equalsIgnoreCase("xyz", null) = false
StringUtils.equalsIgnoreCase("xyz", "xyz") = true
StringUtils.equalsIgnoreCase("xyz", "XYZ") = true
You can use java.util.Objects as following.
public static boolean compare(String str1, String str2) {
return Objects.equals(str1, str2);
}
boolean compare(String str1, String str2) {
if(str1==null || str2==null) {
//return false; if you assume null not equal to null
return str1==str2;
}
return str1.equals(str2);
}
is this what you desired?
boolean compare(String str1, String str2) {
if (str1 == null || str2 == null)
return str1 == str2;
return str1.equals(str2);
}
boolean compare(String str1, String str2) {
return (str1==null || str2==null) ? str1 == str2 : str1.equals(str2);
}
OK, so what does "best possible solution" mean?
If you mean most readable, then all the possible solutions are pretty much equivalent for an experienced Java programmer. But IMO the most readable is this
public boolean compareStringsOrNulls(String str1, String str2) {
// Implement it how you like
}
In other words, hide the implementation inside a simple method that (ideally) can be inlined.
(You could also "out-source" to a 3rd party utility library ... if you already use it in your codebase.)
If you mean most performant, then:
the most performant solution depends on the platform and the context,
one of the "context" issues is the relative (dynamic) frequency of occurrence of null arguments,
it probably doesn't matter which version is faster ... because the difference is probably too small to make a difference to the overall application performance, and
if it does matter, the only way to figure out which is fastest ON YOUR PLATFORM is to try both versions and measure the difference.