Regarding String comparision - java

I was checking the string comparison methods used for string compsrsion and explore the string class in the decomplier and come to know that there are basically four methods
equals()
equalsIgnoreCase()
compareTo()
compareToIgnore()
Now I want to know the difference between two methods that we use they are equals() and compareTo() , basically please advise why string class had kept both these methods ..
String tv = "Bravia";
String television = "Bravia";
// String compare example using equals
if (tv.equals(television)) {
System.out.println("Both tv and television contains same letters and equal by equals method of String");
}
// String compare example in java using compareTo
if (tv.compareTo(television) == 0) {
System.out.println("Both tv and television are equal using compareTo method of String");
}
output :-
Both tv and television contains same letters and equal by equals method of String
Both tv and television are equal using compareTo method of String

equals() returns a boolean; true/false. Is string A equal to B?
compareTo() returns an integer, representing not only whether the strings are equal, but which one is "lower" than the other - with "lower" defined as the natural alphabetical ordering.
For two strings a and b, a.equals(b) is true if an only if a.compareTo(b) is 0.
For example:
String a = "String1";
String b = "String2";
a.compareTo(b) will return a negative integer (not necessarily -1!), because, alphabetically, the string "String1" is lower than "String2"; if you were to sort the two strings in ascending order, "String1" would come first. Also, a.equals(b) will return false, because the strings are not equal.
However:
String a = "Example";
String b = "Example";
In this case, a.compareTo(b) will return 0 (because the strings are equal), and a.equals(b) will return true (again, because the strings are equal).
With respect to the "ignoreCase" variants:
String a = "String1";
String b = "string1";
In this case, a.compareToIgnoreCase(b) will return 0; that's because, when case is ignored, the two strings are identical. Also, a.equalsIgnoreCase(b) will return 0, for the same reason.

equals and equalsIgnoreCase return a boolean value that say "one is either equal to another, or is not"
compareTo and compareToIgnoreCase() return a tristate integer, 0, -1 or 1
0 if they're equal comparing each ordinally
1 if the
argument to compareTo*() is greater in ordinal than the object you invoke compareTo*() on
-1 if the argument to compareTo*() is lesser in
ordinal than the object you invoke compareTo*() on.

Strings implement Comparable interface and then its bound to implement compareTo method.
Camparable interface
it facilitates ordering of the object when they are contained in any sorted collection. So when you will put your string in any sorted collection(like TreeSet), how will you tell java how to sort your objects. that's where coompareTo() method comes in seen. it is used by collection to sort your object.
String tv = "Bravia";
String television = "Bravia";
// String compare example using equals
if (tv.equals(television)) {
System.out.println("Both tv and television contains same letters and equal by equals method of String");
}
// String compare example in java using compareTo
if (tv.compareTo(television) == 0) {
System.out.println("Both tv and television are equal using compareTo method of String");
}
if (tv.compareTo(television) < 0){
System.out.println("tv comes before using compareTo method of String");
}
if (tv.compareTo(television) > 0){
System.out.println("tv comes after using compareTo method of String");
}

Both methods are needed. String inherits equals from Object, and compareTo is required when implementing the Comparable interface.

compareTo(): return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. from compareTo()
equals(): The equals() method compares two objects for equality and returns true if they are equals else return false source here

Related

dosent understand how sort works

I'm trying to understand how the comparable compareTo method sort the input. Below is the compareTo method implemented:
#Override
public int compareTo(Name n) {
int lastCmp = lastName.compareTo(n.lastName);
return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName));
}
The input array to the Collections.sort method is:
Name nameArray[] = {
new Name("John","Smith"),
new Name("Karl","Ng"),
new Name("Jeff","Smith"),
new Name("Tom","Rich")
};
List<Name> names = Arrays.asList(nameArray);
Collections.sort(names);
I don't understand what values are taken in to the compareTo method. (n.lastName and lastname) in which order?
The Collections.sort() method uses different algorithms to sort depending on the collection length and type (I think...)
The compareTo method should return negatives, 0, or positives if the object is less-than, equal or greater-than respectively.
the lastName variable refers to the Last Name in the Name class, composed of firstName:String and lastName:String.
The method first compares the lastName (object of type String) to the lastName of the passed object "n" (of type Name). If it is different than 0 (meaning not equal) return that value. If it is equal then compare the first name and return that.
So it is only comparing the two strings (firstName and lastName of the Name objects).

How the equals() method works

I am digging into the basics of Java. I infer from this article, that the Java 'equals' method means, if two objects are equal then they must have the same hashCode().
Here's my example.
public class Equals {
/**
* #param args
*/
public static void main(String[] args) {
String a = new String("a");
String b = new String("a");
System.out.println("a.hashCode() "+a.hashCode());
System.out.println("b.hashCode() "+b.hashCode());
System.out.println(a == b);
System.out.println(a.equals(b));
}
}
Output:
a.hashCode() 97
b.hashCode() 97
false
true
The actual Java language 'equals' method:
public boolean equals(Object obj) {
return (this == obj);
}
In my above example, a.equals(b) has returned true, meaning the condition 'a==b' is satisfied. But then why is 'a==b' returning false in that example?
Aren't hashCode and address one and same? Also, is 'hashCode' compared when we say 'a==b' or something else?
The String class has overridden the equals() method. Please follow the String equals() documentation.
a.equals(b) has returned true, meaning the condition a==b is satisfied
This is the default implementation of equals() in the Object class, and the String class has overridden the default implementation. It returns true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
Aren't hashCode and address one and same?
Not necessarily. For further reading on hashCode().
The == operator in Java compares object references to see if they refer to the same object. Because your variables a and b refer to different objects, they are not equal according to ==.
And the hashCode method doesn't return the address in String, because that class has overridden hashCode.
Additionally, the equals method has been implemented in String to compare the contents of the strings; that's why a.equals(b) returns true here.
No, Hashcode and address aren't the same.
Because a==b is not comparing hashcodes.
Yes, something else is compared when we say a==b.
(that's not addresses either, really, but it's close enough).
Also, just because "equal objects have equal hashcodes" does not mean "equal hashcodes means equal objects".
a.equals(b) is different from a==b.
a.equals(b) checks if two objects are equals based on equals() implementation.
a==b checks if two objects have same reference.
If a==b is true then a.equals(b) must be true because they are referencing to the same object but not vice-versa.
String class overrides the default implementation of the equals() method of the Object class. The equals method code that you have provided is not from String class but from the Object class, which is overridden be the String class implementation which checks if the contents of the two objects are same or not.
Hashcode for an object is meant to be overridden.
For String class the formula used is as follows:
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
I encourage you to search why 31 has been used as a multiplier and not some other number.
A general thumb rule for overriding hash code is that for different objects hash code should be different as far as possible.
To achieve this it is advisable that you take into account every significant field of an object while calculating the hash value.
Note: Just an unrelated food for thought (source : Effective Java):
Consider the following implementation of hashcode
int hashcode(){
return 10;
}
This is a valid implementation but it is also the worst possible one. Read about why.
A and B are two separate objects that generate the same hash code because of String's implementation of hashCode(). == just checks to see if the left and right sides share the same reference. It does not call an Object's equals() method.
So, no, hashes and object references are not the same thing.
public class TestEquals {
/**
* #param args
*/
public static void main(String[] args) {
String a = new String("a");
String b = new String("a");
System.out.println("a.hashCode() " + a.hashCode());
System.out.println("b.hashCode() " + b.hashCode());
// Checks the reference which is something like the
// address & address is different from hash code which can be overriden
System.out.println(a == b);
// It returns true if and only if the argument is not null
// and is a String object that represents the same sequence
// of characters as this object. (String Implementation of equals)
System.out.println(a.equals(b));
}
}
Output:
a.hashCode() 97
b.hashCode() 97
false
true

String CompareTo not working

I have a simple if statement that doesn't seem to work. I'm out of ideas. I don't understand why my logic is wrong.
String a = "bf";
if (a.compareTo("bf"))
{
// do this
}
I'm getting a redline under the compareTo statement.
Type mismatch: cannot convert from int to boolean
compareTo method returns int value. so do as
if (a.compareTo("bf") == 0)
{
//
}
(or)
use .equals method
if (a.equals("bf"))
{
// do this
}
compareTo returns an int, not a boolean.
http://developer.android.com/reference/java/lang/Comparable.html
It a negative integer if this instance is less than another; a positive integer if this instance is greater than another; 0 if this instance has the same order as another.
So you should check for == 0
By the way, it works for things that can be ordered only. If you just want to check for equality, use .equals
change it to this
String a = "bf";
if (a.compareTo("bf") == 0)
{
// do this
}
The compareTo method returns an int value, not a boolean.
You must change it to
if (a.compareTo("bf") == 0)
or use
if (a.equals("bf"))
When comparing for equality you should use equals(), because it
expresses your intent in a clear way.
compareTo() has the additional drawback that it only works on objects
that implement the Comparable interface.
This applies in general, not only for strings.
Use equals() method of Object class to compare two String objects here.
String a = "bf";
if (a.equals("bf"))
{
// do this
}
Moreover compareTo() is the method of java.lang.Comparable Interface.
compareto returns an integer. An if statement wants a boolean to check so change you code to:
String a = "bf";
if (a.compareTo("bf")==0)
{
// do this
}

how to check reference equality in an object which implements content equality?

...in other words:
let's suppose I have 2 Strings declared as so:
String one = new String("yay!");
String two = new String("yay!");
these two Strings are two different objects, but if I run
if(one.equals(two))
System.out.println("equals() returns true.");
I get "equals() returns true".
This is because the String class overrides the equals() method to implement a content level equality.
However, I need to access a reference level equality (like the one implemented in Object) to distinguish the object one form the object two.
How can I do that?
I tried this:
one.getClass().getSuperclass().equals();
to try to invoke the Object equals() method of the String one but it didn't work.
Any advice?
If you want to check reference just perform:
one == two
But be careful with strings. There is a thing called String constant pool so they may refer to the same object.
String in java uses a String Literal Pool, this means is: "When you try construct a string, first String class search in Literal Pool for traditional same string ,if exist return it, and if don't exist create it", so you can't check by equals method compare refernce of String instance, you have to use == operator as following:
String one = new String("yay!");
String two = new String("yay!");
if(one.equals(two))
System.out.println("equals() returns true.");
if(one == two)
System.out.println(" == operator returns true.");
result is :
equals() returns true.
see following link for more information:
http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/
Java String.equals versus ==
Use simple == comparison. However to avoid String interning you have to create your Strings using char arrays such as: String me = new String(new char[] { 'm', 'e' }); instead of using String literals "me" such as String me = new String("me");.
if (one == two)
System.out.println("one and two are the same object");
The only this you need is "==" equality operator.

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