Sunday, August 1, 2010

String equals() method

Its about how String's equals() method works -

1. Firstly it compare references of two string objects to be compared. If references are same then two string object' value are equal and no need for further comparision.

2. If references are not equal, then it compare the value of two string object by comparing the string's on character by character basis.

public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}

No comments:

Post a Comment