Como comparar um array em java

Java Programming Java 8Object Oriented Programming

Arrays can be compared using following ways in Java

  • Using Arrays.equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method.

  • Using Arrays.deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.

Using == on array will not give the desired result and it will compare them as objects. See the example below for each of the comparison way.

Example

 Live Demo

import java.util.Arrays; public class Tester{    public static void main(String[] args) {       int[] array1 = {1, 2, 3};       int[] array2 = {1, 2, 3};       System.out.println("Arrays: array1 = [1, 2, 3], array 2 = [1, 2, 3]");       //Scenario 1 : Comparing using ==       System.out.println("== results: " + (array1 == array2));       //Scenario 2 : Comparing using Arrays.equals()       System.out.println("Arrays.equals() results: " + Arrays.equals(array1,array2));       Object[] objArray1 = {array1};       Object[] objArray2 = {array2};       System.out.println("Arrays: objArray1 = {array1}, objArray1 = {array2}");       //Scenario 3 : Comparing using Arrays.equals()       System.out.println("Arrays.equals() results: " + Arrays.equals(objArray1,objArray2));       //Scenario 4 : Comparing using Arrays.deepEquals()       System.out.println("Arrays.deepEquals() results: " + Arrays.deepEquals(objArray1,objArray2));    } }

Output

Arrays: array1 = [1, 2, 3], array 2 = [1, 2, 3] == results: false Arrays.equals() results: true Arrays: objArray1 = {array1}, objArray1 = {array2} Arrays.equals() results: false Arrays.deepEquals() results: true

Como comparar um array em java

Updated on 22-Jun-2020 11:31:37

In Java, we can compare two arrays by comparing each element of the array. Java Arrays class provides two predefined methods that is used to compare two arrays in Java.

In this section, we will learn how to compare two Arrays using Arrays.equals() method and Arrays.deepEquals() method. Along with this, we will also learn how to perform a deep comparison between the two arrays with proper examples.

Two arrays are equal if:

  • They are of the same type.
  • They have an equal number of elements.
  • Corresponding pairs of elements in both arrays must be equal.
  • The order of elements must be the same.
  • Two array references are equal if they are null.

Before moving to the topic, first, consider the following example and guess the output.

ArrayEqualsExample1.java

public class ArrayEqualsExample1 { public static void main (String[] args) { //defining arrays to be compare int[] a1 = new int[] {1, 2, 3, 4, 5, 6, 7, 8}; int[] a2 = new int[] {1, 2, 3, 4, 5, 6, 7, 8}; //comparing references using == operator //works the same as a1.equals(a2) if (a1 == a2) System.out.println("Arrays are equal."); else System.out.println("Arrays are not equal."); } }

Output:

In the above example, a1 and a2 are the two references of two different objects. When we compare two reference variables, we get the output Arrays are not equal, while both the arrays are of equal length, and having the same elements. We are not getting the desired output because the equals (==) operator compare them as an object.

Now, we have only an option to compare two arrays, i.e. compare the content (elements) of the array. Let's see how to compare array contents.

It will be good if we compare the elements one by one. To compare the content of the array Java Arrays class provides the following two methods to compare two arrays:

  • equals() Method
  • deepEquals() Method

Arrays.equals() Method

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.

Syntax:

public static boolean equals(int[] a1, int[] a2)

It parses two arrays a1 and a2 that are to compare. The method returns true if arrays are equal, else returns false. The Arrays class has a list of overloaded equals() method for different primitive types and one for an Object type.

Note: While using the array of objects, don't forget to override the equals() method. Otherwise, we will get the output returned by the equals() method of the Object class.

ArrayEqualsExample2.java

import java.util.Arrays; public class ArrayEqualsExample2 { public static void main (String[] args) { //defining array to compare int[] array1 = new int[] {'a', 'b', 'c', 'd', 'e'}; int[] array2 = new int[] {'a', 'b', 'c', 'd', 'e'}; //comparing two arrays using equals() method if (Arrays.equals(array1, array2)) System.out.println("Arrays are equal."); else System.out.println("Arrays are not equal."); } }

Output:

Let's see another example.

ArrayEqualsExample3.java

import java.util.Arrays; public class ArrayEqualsExample3 { public static void main (String[] args) { //defining arrays to compare int[] array1 = new int [] {21, 32, 36, 47}; int[] array2 = new int [] {11, 22, 33, 44}; int[] array3 = new int [] {21, 32, 36, 47}; System.out.println("Are array1 and array2 equal?" + Arrays.equals(array1, array2)); System.out.println("Are array1 and array3 equal?" + Arrays.equals(array1, array3)); } }

Output:

Are array1 and array2 equal? false Are array1 and array3 equal? true

We see that the Arrays.equals() method compares the elements of the array. Here, a question arises that what if an array has nested array or some other references which refer to different object but have the same values.

Let's understand it through the following example.

ArrayEqualsExample4.java

import java.util.Arrays; public class ArrayEqualsExample4 { public static void main (String[] args) { //defining array to compare String[] inarray1 = new String[] {"mango", "grapes", "plum", "watermelon", "apple"}; String[] inarray2 = new String[] {"mango", "grapes", "plum", "watermelon", "apple"}; Object[] array1 = {inarray1}; // array1 have only one element Object[] array2 = {inarray2}; // array2 also have only one element //comparing two arrays using equals() method if (Arrays.equals(array1, array2)) System.out.println("Arrays are equal."); else System.out.println("Arrays are not equal."); } }

Output:

In the above example, we see that the equals() method is not able to perform a deep comparison. To resolve this problem, the Java Arrays class provides another method deepEquals() that deeply compares the two arrays.

Arrays.deepEquals() Method

Java Arrays class provides another method deepEquals() to deeply compare the array. Here, deeply compare means it can compare two nested arrays of arbitrary depth. Two arrays object reference e1 and e2 are deeply equal if they hold any of the following condition:

  • e1=e2
  • equals(e2) returns true.
  • If e1 and e2 are both the same primitive type the overloading of the method Arrays.equals(e1, e2) returns true.
  • If e1 and e2 are both arrays of object reference types, the method Arrays.deepEquals(e1, e2) returns true.

Syntax:

public static boolean deepEquals(Object[] a1, Object[] a2)

The method parses the two arrays a1 and a2 that is to compare. It returns true if both arrays are deeply equal, else returns false.

Let's create a program and deeply compare two arrays using the deepEquals() method of the Arrays class.

ArrayEqualsExample5.java

import java.util.Arrays; public class ArrayEqualsExample5 { public static void main (String[] args) { //defining array to compare String[] inarray1 = new String[] {"mango", "grapes", "plum", "watermelon", "apple"}; String[] inarray2 = new String[] {"mango", "grapes", "plum", "watermelon", "apple"}; Object[] array1 = {inarray1}; // array1 have only one element Object[] array2 = {inarray2}; // array2 also have only one element //comparing two arrays using equals() method if (Arrays.deepEquals(array1, array2)) System.out.println("Arrays are equal."); else System.out.println("Arrays are not equal."); } }

Output:

Next TopicHow to Convert String to JSON Object in Java

Galera,

Sou iniciante em JAVA, e uma das coisas que mais odeio em programação é VETOR/ARRAY.
Estou com um exercício da faculdade para fazer.

Segue o código:

[code]package FEUC;

import java.util.Scanner;

public class Exerc4 {

/* Escreva um programa que calcula o máximo, * o mínimo, a soma e a média de um conjunto * de valores inteiros. O número de valores a * introduzir deve ser também pedido ao utilizador. */ public static void main(String[] args) { Scanner scan = new Scanner(System.in); int[] valores = new int[5]; // vetor de 5 posições int maximo = 0; int minimo = 0; int soma; double media; int i; for (i=0;i<5;i++) { System.out.println("Informe o valor do " + (i+1) + "º valor: " ); valores[i] = scan.nextInt(); } }

}[/code]

Minha dificuldade é fazer a comparação entre os valores de um único array.

Poderiam me dá o “caminho das pedras”?

Abs.

O que você quer comparar? por que? pra que?

Como comparar um array em java

O usuário vai entrar com 5 valores, e estes serão guardados no vetor.
Destes 5 valores, quero saber o maior e o menor, fazer a soma e a média.

Segue abaixo o enunciado:

/* Escreva um programa que calcula o máximo, * o mínimo, a soma e a média de um conjunto * de valores inteiros. O número de valores a * introduzir deve ser também pedido ao utilizador. */

Abs,

Sabe comparar valores? maior, maior ou igual… coisas assim?

Faça mais um laço no seu sistema percorrendo o vetor e comparando os números, dentro do laço vc tbm pode fazer a soma dentro deste mesmo laço e qdo for mostrar o resultado calcula a média, simples assim!

Olhem como eu fiz:

[code] package FEUC;

import java.util.Scanner;

public class Exerc4 {

/* Escreva um programa que calcula o máximo, * o mínimo, a soma e a média de um conjunto * de valores inteiros. O número de valores a * introduzir deve ser também pedido ao utilizador. */ public static void main(String[] args) { Scanner scan = new Scanner(System.in); int[] valores = new int[5]; // vetor de 5 posições int maior = 0; int menor = 0; int soma; double media; int i; for (i=0;i<5;i++) { System.out.println("Informe o valor do " + (i+1) + "º valor: " ); valores[i] = scan.nextInt(); } if ((valores[1] > valores[2]) && (valores[1] > valores[3]) && (valores[1] > valores[4]) && (valores[1] > valores[5])) { maior = valores[1]; System.out.println("O maior valor é " + valores[1]); } if ((valores[2] > valores[1]) && (valores[2] > valores[3]) && (valores[2] > valores[4]) && (valores[2] > valores[5])) { maior = valores[2]; System.out.println("O maior valor é " + valores[2]); } if ((valores[3] > valores[1]) && (valores[3] > valores[3]) && (valores[3] > valores[4]) && (valores[3] > valores[5])) { maior = valores[3]; System.out.println("O maior valor é " + valores[3]); } if ((valores[4] > valores[1]) && (valores[4] > valores[2]) && (valores[4] > valores[3]) && (valores[4] > valores[5])) { maior = valores[4]; System.out.println("O maior valor é " + valores[4]); } if ((valores[5] > valores[1]) && (valores[5] > valores[2]) && (valores[5] > valores[3]) && (valores[5] > valores[4])) { maior = valores[5]; System.out.println("O maior valor é " + valores[5]); } if ((valores[1] < valores[2]) && (valores[1] < valores[3]) && (valores[1] < valores[4]) && (valores[1] < valores[5])) { menor = valores[1]; System.out.println("O menor valor é " + valores[1]); } if ((valores[2] < valores[1]) && (valores[2] < valores[3]) && (valores[2] < valores[4]) && (valores[2] < valores[5])) { menor = valores[2]; System.out.println("O menor valor é " + valores[2]); } if ((valores[3] < valores[1]) && (valores[3] < valores[3]) && (valores[3] < valores[4]) && (valores[3] < valores[5])) { menor = valores[3]; System.out.println("O menor valor é " + valores[3]); } if ((valores[4] < valores[1]) && (valores[4] < valores[2]) && (valores[4] < valores[3]) && (valores[4] < valores[5])) { menor = valores[4]; System.out.println("O menor valor é " + valores[4]); } if ((valores[5] < valores[1]) && (valores[5] < valores[2]) && (valores[5] < valores[3]) && (valores[5] < valores[4])) { menor = valores[5]; System.out.println("O menor valor é " + valores[5]); } media = (valores[1] + valores[2] + valores[3] + valores[4] + valores[5]) / 5; soma = (valores[1] + valores[2] + valores[3] + valores[4] + valores[5]); System.out.println("A média dos valores é " + media + " e a soma dos valores é " + soma); }

}
[/code]

Tem como melhorar?

Abs,

[quote=juliomendes90]Olhem como eu fiz:
Tem como melhorar?[/quote]

Com certeza tem:

public static void main(String[] args) { Scanner scan = new Scanner(System.in); int[] valores = new int[5]; // vetor de 5 posições int maior = 0; int menor = 0; int soma; double media; for (int i = 0; i < 5; i++) { System.out.println("Informe o valor do " + (i + 1) + "º valor: " ); valores[i] = scan.nextInt(); } // Add os primeiros valores às variáveis menor = valores[0]; maior = valores[0]; for (int i = 0; i < valores.length(); i++) { soma += valores[i]; //soma os valores if (menor > valores[i]) menor = valores[i]; // Verifica e add o menor valor if (maior < valores[i]) maior = valores[i]; // Verifica e add o maior valor } // Calcula a média media = soma / valores.length; // print para mostrar os valores, soma e média... }

Uma obs, vc pode declarar o “int i” diretamente dentro do laço for, é uma variável a menos no scopo do método.

Por favor, não abuse do CAPS LOCK no título das suas mensagens.

[quote=fabiocortolan][quote=juliomendes90]Olhem como eu fiz:
Tem como melhorar?[/quote]

Com certeza tem:

public static void main(String[] args) { Scanner scan = new Scanner(System.in); int[] valores = new int[5]; // vetor de 5 posições int maior = 0; int menor = 0; int soma; double media; for (int i = 0; i < 5; i++) { System.out.println("Informe o valor do " + (i + 1) + "º valor: " ); valores[i] = scan.nextInt(); } // Add os primeiros valores às variáveis menor = valores[0]; maior = valores[0]; for (int i = 0; i < valores.length(); i++) { soma += valores[i]; //soma os valores if (menor > valores[i]) menor = valores[i]; // Verifica e add o menor valor if (maior < valores[i]) maior = valores[i]; // Verifica e add o maior valor } // Calcula a média media = soma / valores.length; // print para mostrar os valores, soma e média... }

Uma obs, vc pode declarar o “int i” diretamente dentro do laço for, é uma variável a menos no scopo do método.[/quote]

Valeu amigo, obrigado.

Como comparar um array em java
ViniGodoy:

Por favor, não abuse do CAPS LOCK no título das suas mensagens.

Beleza, obrigado. Até então, não sabia dessa regra. Abs,