What is an efficient way to compare StringBuilder objects - java

Well I have two StringBuilder objects, I need to compare them in Java.
One way I know I can do is
sb1.toString().equals(sb2.toString());
but that means I am creating two String objects, is there any better way to compare StringBuilder objects. Probably something where you do not need to create additional objects?

As you apparently already know, StringBuilder inherits equals() from java.lang.Object, and as such StringBuilder.equals() returns true only when passed the same object as an argument. It does not compare the contents of two StringBuilders!
If you look at the source, you'll conclude that the most efficient comparison (that didn't involve creating any new objects) would be to compare .length() return values, and then if they're the same, compare the return values of charAt(i) for each character.

Since Java 11, StringBuilder implements Comparable, so you can use a compareTo method for the equality test:
System.out.println(sb1.compareTo(sb2) == 0);

Two StringBuilder objects are never equal. Use .toString() to get the string representation for both the objects and then use .equals() to compare the objects. This way equals() method from the String class gets invoked that compares the string value of the objects instead of comparing the memory location.
StringBuilder a= new StringBuilder("HELLO JAVA");
StringBuilder b= new StringBuilder("HELLO JAVA");
if (a.toString().equals(b.toString())){
System.out.println("Objects are equal");
}

A solution without new allocations would be to compare first at length, and if it differs, then char by char. This is more efficient and faster than performing a compare via a toString() on the StringBuilder call, which would allocate a new string.
The next snipped assumes both parameters aren't null neither the same object instance:
public boolean compare(final StringBuilder left, final StringBuilder right) {
final int length = left.length();
if (length != right.length())
return false;
for (int index = 0; index < length; index++) {
if (left.charAt(index) != right.charAt(index))
return false;
}
return true;
}

Related

I didn't understand why I am getting false, instead of getting true, please look into the code and help me [duplicate]

int [] nir1 = new int [2];
nir1[1] = 1;
nir1[0] = 0;
int [] nir2 = new int [2];
nir2[1] = 1;
nir2[0] = 0;
boolean t = nir1.equals(nir2);
boolean m = nir1.toString().equals(nir2.toString());
Why are both m and t false? What is the correct way to compare 2 arrays in Java?
Use Arrays.equals method. Example:
boolean b = Arrays.equals(nir1, nir2); //prints true in this case
The reason t returns false is because arrays use the methods available to an Object. Since this is using Object#equals(), it returns false because nir1 and nir2 are not the same object.
In the case of m, the same idea holds. Object#toString() prints out an object identifier. In my case when I printed them out and checked them, the result was
nir1 = [I#3e25a5
nir2 = [I#19821f
Which are, of course, not the same.
CoolBeans is correct; use the static Arrays.equals() method to compare them.
Use Arrays.equals instead of array1.equals(array2). Arrays.equals(array1, array2) will check the content of the two arrays and the later will check the reference. array1.equals(array2) simply means array1 == array2 which is not true in this case.
public static boolean perm (String s, String t){
if (s.length() != t.length()) {
return false;
}
char[] perm1 = s.toCharArray();
Arrays.sort(perm1);
char[] perm2 = t.toCharArray();
Arrays.sort(perm2);
return Arrays.equals(perm1, perm2);
}
boolean t = Arrays.equals(nir1,nir2)
I just wanted to point out the reason this is failing:
arrays are not Objects, they are primitive types.
When you print nir1.toString(), you get a java identifier of nir1 in textual form. Since nir1 and nir2 were allocated seperately, they are unique and this will produce different values for toString().
The two arrays are also not equal for the same reason. They are separate variables, even if they have the same content.
Like suggested by other posters, the way to go is by using the Arrays class:
Arrays.toString(nir1);
and
Arrays.deepToString(nir1);
for complex arrays.
Also, for equality:
Arrays.equals(nir1,nir2);
Use this:
return Arrays.equals(perm1, perm2)
Instead of this:
return perm1.equals(perm2);
Please have to look this

Arrays comparation in java [duplicate]

int [] nir1 = new int [2];
nir1[1] = 1;
nir1[0] = 0;
int [] nir2 = new int [2];
nir2[1] = 1;
nir2[0] = 0;
boolean t = nir1.equals(nir2);
boolean m = nir1.toString().equals(nir2.toString());
Why are both m and t false? What is the correct way to compare 2 arrays in Java?
Use Arrays.equals method. Example:
boolean b = Arrays.equals(nir1, nir2); //prints true in this case
The reason t returns false is because arrays use the methods available to an Object. Since this is using Object#equals(), it returns false because nir1 and nir2 are not the same object.
In the case of m, the same idea holds. Object#toString() prints out an object identifier. In my case when I printed them out and checked them, the result was
nir1 = [I#3e25a5
nir2 = [I#19821f
Which are, of course, not the same.
CoolBeans is correct; use the static Arrays.equals() method to compare them.
Use Arrays.equals instead of array1.equals(array2). Arrays.equals(array1, array2) will check the content of the two arrays and the later will check the reference. array1.equals(array2) simply means array1 == array2 which is not true in this case.
public static boolean perm (String s, String t){
if (s.length() != t.length()) {
return false;
}
char[] perm1 = s.toCharArray();
Arrays.sort(perm1);
char[] perm2 = t.toCharArray();
Arrays.sort(perm2);
return Arrays.equals(perm1, perm2);
}
boolean t = Arrays.equals(nir1,nir2)
I just wanted to point out the reason this is failing:
arrays are not Objects, they are primitive types.
When you print nir1.toString(), you get a java identifier of nir1 in textual form. Since nir1 and nir2 were allocated seperately, they are unique and this will produce different values for toString().
The two arrays are also not equal for the same reason. They are separate variables, even if they have the same content.
Like suggested by other posters, the way to go is by using the Arrays class:
Arrays.toString(nir1);
and
Arrays.deepToString(nir1);
for complex arrays.
Also, for equality:
Arrays.equals(nir1,nir2);
Use this:
return Arrays.equals(perm1, perm2)
Instead of this:
return perm1.equals(perm2);
Please have to look this

Why is String equals not working in my code?

I have already checked two compared strings, but even the value parameter str and temp is printed both "mn". The str.equals(temp) is still returning false.
public int strStr(String haystack, String needle) {
StringBuffer str=new StringBuffer(needle);
int result=-1;
for(int i=0;i<=haystack.length()-needle.length();i++){
StringBuffer temp = new StringBuffer(haystack.substring(i, i+needle.length()));
System.out.println(temp.equals(str));
System.out.println(temp+"="+str);
if (str.equals(temp)){
result=i;
break;
}
}
return result;
}
You are comparing two StringBuffer objects. The equals(Object) method for StringBuffer is inherited from Object, and is defined to be the same as comparing the object references.
The objects are different, and therefore, the result is false in your example.
Try this instead:
if (str.toString().equals(temp.toString())){
This works because the String.equals(Object) compares the string values, not the string object references. (But note that you have to convert both StringBuffer objects, because String.equals(Object) will always return false if the argument is not a String object.)
Note also that using str as the name for a StringBuffer variable is highly misleading. Most people would expect something called str to be a String. (I did!!)
FWIW, I was scratching my head for a more efficient way to compare the contents of two StringBuffer objects. The above code creates and discards two temporary String objects. The best I can come up with is to code it by hand; e.g. something like this:
public boolean equalBuffers(StringBuffer sb1, StringBuffer sb2) {
if (sb1 == sb2) {
return true;
}
int len = sb1.length();
if (len != sb2.length()) {
return false;
}
for (int i = 0; i < len; i++) {
if (sb1.charAt(i) != sb2.charAt(i)) {
return false;
}
}
return true;
}
You are comparing the references to the StringBuffer objects rather than the actual strings.And
StringBuffer class doesn't override the equals() method of Object class.
Try this
str.toString().equals(temp.toString())
The java.lang.StringBuffer.toString() method returns a string representing the data in this sequence.
A new String object is allocated and initialized to contain the character sequence currently represented by this object. This String is then returned.
thats why you can compare two StringBuffer object by converting them into string.
You are comparing StringBuffer with String so the equals method always return false.
str.equals(temp.toString())
But you need to know another important concept here when you does
System.out.println(temp+"="+str);
you are printing temp which is stringbuilder, java internally calls temp.toString() to achieve this.

Java comparing strings [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
i have a small of a problem. I have to String Lists with the same size and a string to compare. meaning i want to compare the string with the first list to get the index of the compared string in the list and then get another string from the other list on this index.
private String getStringOnIndex(List<String> list1, List<String> list2,String elem)
{
String elem2;
for (int i = 0; i<list1.size();i++) {
if(list1.get(i).equals(elem)){
elem2 = list2.get(i);
return elem2;
} else {
return "nope";
}
}
}
Is it wrong to compare two strings like that. or should i use the operator ==. I know the style with to string lists is not nice but its just a temporary solution. thx for any help :)
To answer your specific question on "string comparison", what you are doing is correct. String content comparison should be done using equals(). Using operator == is only checking for the equality of the reference, not the content.
For the work you are doing now, it looks like a key-value lookup to me. You may consider some redesign and, instead of storing 2 lists, make a Map<String, String>
== operator in Java compares the Object References, to compare strings you should use equals().
if (list1.get(i).matches(elem))....
always use equals method to compare two string. If you are comparing references then use == operator. Here discussion can be useful How do I compare strings in Java?
== operator work fine only if the String variable is not instanciated new keyword.
Suppose:
String s1 = "abc";
String s2 = "abc";
Then s1==s2 works good.
If:
String s1 = new String("abc");
String s2 = new String("abc");
Then you must use equals method to compare the values.
Finally, it is always better to use equals method to compare the String values.
Use the equals() method to compare the value of the object,where as == operator will compare object reference.
The problem is not equals (that is the correct method), you must remove else expression, if not you will stop always at first iteration, solution:
private String getStringOnIndex(List<String> list1, List<String> list2,String elem)
{
String elem2;
for (int i = 0; i<list1.size();i++) {
if(list1.get(i).equals(elem)){
elem2 = list2.get(i);
return elem2;
}
}
return "nope";
}

read ArrayList elements

Why it print the wrong output?
ArrayList<String> loc = new ArrayList<String>();
This arraylist stored the value of:
[topLeft, topLeft, topLeft, bottomLeft, topLeft, bottomLeft, topLeft, topLeft, Left, topLeft]
the firs index 0 is = topLeft
if(loc.get(1)=="topLeft")
System.out.println("same")
else {
System.out.println("not same")
}
This program print the wrong output not same instead of same
Use the equals(Object) method, not the == operator, for example loc.equals("topLeft")
The == operator returns true if two references point to the same Object in memory. The equals(Object o) method checks whether the two objects are equivalent, so will return true if two Strings contain only the same characters in the same order.
String comparison is done by calling str1.equals(str2) rather than using ==.
equals(..) compares the strings' contents
== compares the references, and they are not the same.
There is a little more to know, however. String objects that are initialized as literals, i.e.
String str = "someString"
instead of via construction (String str = new String("some")) are all the same object. For them == would work.
And finally, for any String, calling intern() returns a String that is the same object as all other strings with the same content. (read intern()'s documentation for more info)
But the best practice here is to use equals(), while being careful if the object you are calling it on (the first string) is not null.

Categories