Documente Academic
Documente Profesional
Documente Cultură
com/java-sorting-algorithms/
http://www.geeksforgeeks.org/sorting-algorithms/
http://javaconceptoftheday.com/java-interview-programs-with-solutions/
Two arrays are said to be equal if the arrays have equal number of elements and all corresponding
pairs of elements in two arrays are equal. In the other words, two arrays are said to be equal if both
the arrays have same elements in the same order. You are very often need to compare two arrays for
equality while developing the applications. This is also one of the important java interview question
for 1 or 2 years experienced java professionals.
In this post, I have tried to point out different methods to check the equality of two arrays.
1) Iterative Method :
In this method, first we check length of two given arrays. If the length of both arrays is same, then we
compare corresponding pairs of elements of both the arrays. If all corresponding pairs of elements
are equal, then given arrays will be considered as equal. This method will be time consuming if the
arrays have lots of elements. This method is not recommended to check the equality of two arrays if
the arrays are big in size. But in the interview, interviewer may ask you to compare two arrays
without using in-built functions. In that time, this method may help you.
public class EqualityOfTwoArrays
if(arrayOne.length == arrayTwo.length)
if(arrayOne[i] != arrayTwo[i])
equalOrNot = false;
else
equalOrNot = false;
if (equalOrNot)
else
}
}
In this method, we use in-built equals() method of Arrays class to check the equality of two arrays.
This method takes two arrays as parameters and returns true if both the arrays have same number of
elements and corresponding pairs of elements of both arrays are equal.
class EqualityOfTwoArrays
If you want to compare two arrays which have same number of elements and same set of elements
but in different positions, then first sort both arrays using Arrays.sort() method and then compare
using Arrays.equals() method.
class EqualityOfTwoArrays
Arrays.sort(s2);
If you are checking multidimensional arrays for equality, then use deepEquals() method of Arrays class
instead of equals() method. Because, deepEquals() performs deep comparison of both the arrays.