Snippet. Vala. Compare Two Arrays, if Equal

This Vala snippet provides an utility function array_equals, which will compare two arrays.

Function: array_equals

With the function array_equals (see bellow) you can find out, if two arrays are equal to one another. The arrays will be considered equal, if they contain the same number of elements and all corresponding pairs of elements are equal. In other words, the two arrays will be considered equal, if they contain the same elements in the same order. Also the two arrays will be considered equal if both are null.

//======================== START OF FUNCTION ==========================//
// FUNCTION: array_equals                                              //
//=====================================================================//
    /**
     * Returns true if the two specified arrays are equal to one another.
     * 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.
     * Also, two array references are considered equal if both are null.
     * @return true if the two arrays are equal
     */
bool array_equals(G[] array_one, G[] array_two){
    if(array_one.length != array_two.length) return false;
    for (int i=0; i< array_one.length; i++) {
        if(array_one[i] != array_two[i]) {
            return false;
        }
    }
    return true;
}
//=====================================================================//
// FUNCTION: array_equals                                              //
//========================= END OF FUNCTION ===========================//

Use Example

How to use the function array_equals:

// Compare arrays of integers
int[] array_one = {5,2,1,4,5,3,7,9,8};
int[] array_two = {5,2,1,4,5,3,7,9,8};
		
bool result = array_equals(array_one,array_two); // true
		
// Compare arrays of strings
string[] array_three = {"Tom","Jerry"};
string[] array_four = {"Tom","Jerry"};
		
bool result2 = array_equals(array_three,array_four); // true

Updated on: 27 Dec 2024