Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two integer arrays in Java

I am trying to write code to compare two arrays. In the first array I have put my own digits, but the second the array takes numbers from the input file. The size of this array is determined by the first number in the file while the first array is always of size 10. The length must be the same for both arrays as well as the numbers.

My code is below:

public static void compareArrays(int[] array1, int[] array2) {     boolean b = false;     for (int i = 0; i < array2.length; i++) {          for (int a = 0; a < array1.length; a++) {              if (array2[i] == array1[a]) {                 b = true;                 System.out.println("true");             } else {                 b = false;                 System.out.println("False");                 break;             }         }     }        } 
like image 632
user2052514 Avatar asked Feb 15 '13 14:02

user2052514


People also ask

How do you compare 2 arrays in Java?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.

Can we use == to compare arrays in Java?

Java Arrays class provides the equals() method to compare two arrays. It iterates over each value of an array and compares the elements using the equals() method.

Can we compare two integers in Java?

Syntax : public static int compare(int x, int y) Parameter : x : the first int to compare y : the second int to compare Return : This method returns the value zero if (x==y), if (x < y) then it returns a value less than zero and if (x > y) then it returns a value greater than zero. Example :To show working of java.


1 Answers

From what I see you just try to see if they are equal, if this is true, just go with something like this:

boolean areEqual = Arrays.equals(arr1, arr2); 

This is the standard way of doing it.

Please note that the arrays must be also sorted to be considered equal, from the JavaDoc:

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.

Sorry for missing that.

like image 138
comanitza Avatar answered Oct 04 '22 11:10

comanitza