How to compare two string arrays without Java utils
•
Java
Check whether array Arr1 contains the same elements as arr2 in the same order in Java
For example:
isTheSame({"1","2","3"},{"1","3"}) → true
isTheSame({"1",{"2","1","1"}) → false
isTheSame({"1",{"3","2"}) → false
So far I have
public boolean isTheSame(String[] arr1,String[] arr2)
{
if (arr1.length == arr2.length)
{
for (int i = 0; i < arr1.length; i++)
{
if (arr1[i] == arr2[i])
{
return true;
}
}
}
return false;
}
The problem is that it only compares the first element of two arrays
Solution
You are iterating until you find a match You should look for a mismatched string. You should use equals not==
// same as Arrays.equals()
public boolean isTheSame(String[] arr1,String[] arr2) {
if (arr1.length != arr2.length) return false;
for (int i = 0; i < arr1.length; i++)
if (!arr1[i].equals(arr2[i]))
return false;
return true;
}
FYI, this is arrays What equals does when dealing with null values
public static boolean equals(Object[] a,Object[] a2) {
if (a==a2)
return true;
if (a==null || a2==null)
return false;
int length = a.length;
if (a2.length != length)
return false;
for (int i=0; i<length; i++) {
Object o1 = a[i];
Object o2 = a2[i];
if (!(o1==null ? o2==null : o1.equals(o2)))
return false;
}
return true;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
