While I am going through a question in hackerrank. I wrote imperfect code and I got the wrong answer for it but I wonder how I got that
Note: I know that by changing the return statement as return java.util.Arrays.equals(aa,bb);
. I get the correct answer
static boolean isAnagram(String a, String b) {
a=a.toLowerCase();
b=b.toLowerCase();
char aa[]=a.toCharArray();
char bb[]=b.toCharArray();
if(a.length()!=b.length())
return false;
else
{
java.util.Arrays.sort(aa);
java.util.Arrays.sort(bb);
System.out.println(aa.equals(bb));
return aa.equals(bb);
}
Code: to determine whether both the string contains the same frequency of characters and return true for same and false for the opposite respectively. The above code always returning false
It thought as aa is not an instance of String. I came to this phenomenon of seeing the below internal code of String_object.equals(String_object) method.
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
So, I tried the code snippet of my original code with Character class and char array
It is working fine for the Character class but not for the char array.
Character a='a';
Character b='a';
System.out.println(a.equals(b)); //return true
but if we make try with Char array. It returns wrong.
char [] a={'a'};
char [] b={'b'};
System.out.println(a.equals(b));//return false always ( I thought it was because as a is not object of type String.
My doubt: Why it works with the Character class but not for the char array? As per the .equals() method code, it should pass false for Character class too but it is not why?
Sorry for my bad English.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…