An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together.The base value is index 0 and the difference between the two indexes is the offset.
In this program, we need to compare two arrays having elements of float type.
Two arrays are equal if they contain the same elements in the same order. Two array references are considered equal if both are null.
Example:
float[] floatV1 = new float[] { 3.1f, 7.5f, 8.3f };
float[] floatV2 = new float[] { 8.3f, 8.8f, 9.2f };
float[] floatV3 = new float[] { 3.1f, 7.5f, 8.3f };
float[] floatV4 = new float[] { 3.2f, 5.5f, 5.3f };
if we compare the two arrays using Arrays.equals() method, it will return true/false.
Arrays.equals(floatV1, floatV2) will give us false
Arrays.equals(floatV3, floatV4) will give us false
Arrays.equals(floatV1, floatV3) will give us true
There are two ways by which we can compare two float arrays:
- By simply iterating through the whole array and comparing each element one by one.
- Using Arrays.equals(arr1,arr2) method
Method 1: By simply iterating through the whole array and comparing each element one by one.
Java
import java.util.Arrays;
public class GFG {
public static void main(String args[])
{
float [] floatV1 = new float [] { 3 .1f, 7 .5f, 8 .3f };
float [] floatV2 = new float [] { 8 .9f, 8 .8f, 9 .2f };
float [] floatV3 = new float [] { 3 .1f, 7 .5f, 8 .3f };
System.out.println(compareArrays(floatV2, floatV3));
System.out.println(compareArrays(floatV1, floatV3));
System.out.println(compareArrays(floatV1, floatV2));
}
public static boolean compareArrays( float arr1[], float arr2[])
{
if (arr1.length != arr2.length)
return false ;
for ( int i = 0 ; i < arr1.length; i++) {
if (arr1[i] != arr2[i])
return false ;
}
return true ;
}
}
|
Method 2: Using Arrays.equals() method
Syntax:
public static boolean equals(int[] a, int[] a2)
Parameters:
- a – one array to be tested for equality
- a2 – the other array to be tested for equality
Returns: true if the two arrays are equal
Java
import java.util.Arrays;
public class GFG {
public static void main(String args[])
{
float [] floatV1 = new float [] { 3 .1f, 7 .5f, 8 .3f };
float [] floatV2 = new float [] { 8 .9f, 8 .8f, 9 .2f };
float [] floatV3 = new float [] { 3 .1f, 7 .5f, 8 .3f };
float [] floatV4 = new float [] { 3 .4f, 5 .5f, 5 .3f };
System.out.println(Arrays.equals(floatV1, floatV2));
System.out.println(Arrays.equals(floatV2, floatV3));
System.out.println(Arrays.equals(floatV3, floatV4));
System.out.println(Arrays.equals(floatV1, floatV3));
System.out.println(Arrays.equals(floatV1, floatV4));
}
}
|
Outputfalse
false
false
true
false