<pre name="code" class="java">// we need to import java.util.Arrays to use Arrays.equals().
import java.util.Arrays;
class Test
{
public static void main (String[] args)
{
int arr1[] = {1, 2, 3};
int arr2[] = {1, 2, 3};
if (Arrays.equals(arr1, arr2))
System.out.println("Same");
else
System.out.println("Not same");
}
}
Output:
Same
"Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order"
To compare:
1, Either use for loops to compare them two, given that their sizes are same.
2, Or use:
class Test
{
public static void main (String[] args)
{
int arr1[] = {1, 2, 3};
int arr2[] = {1, 2, 3};
if (arr1 == arr2) // Same as arr1.equals(arr2)
System.out.println("Same");
else
System.out.println("Not same");
}
}
Output: Not same
For the same reason, we cannot use hashSet to remove duplicates:
public static void main(String[] args) {
HashSet<int[]> rest = new HashSet<int[]>();
int[] a = {1,2};
int[] b = {1,2};
rest.add(a);
rest.add(b);
rest.add(a);
for(int[] x: rest){
System.out.print(x[0]+" "+x[1]);
System.out.println();
}
}
Output:
1 2
1 2