java – How to compare the content of two vectors?

Question:

public class VetorTurma {

    public static void main(String[] args) {

        int pontuacao = 0,nota,c;
        String nome;  

            Scanner sc = new Scanner(System.in);

            double gabaritoVetor[] = new double[10];
            double notaVetor[] = new double[10]; 

            System.out.println("Digite o gabarito: ");
            for(c=0;c < gabaritoVetor.length;c++){
                System.out.print("Gabarito | questão["+c+"]: ");
            gabaritoVetor[c]=sc.nextDouble();


            }
            int i = 0;
            for(i=0;i < notaVetor.length;i++){
                System.out.print("Questão["+i+"]: ");
                notaVetor[i] = sc.nextDouble();



            }

            if(gabaritoVetor==notaVetor){
                 pontuacao ++;


            }

            System.out.println("Pontuação: "+pontuacao);
     }
    }

The if counter always returns zero. What must be wrong?

OBS: It may seem strange numbers as a template, the right one would be a,b,c,d. But first I want to do it with numbers and then as characters.

Answer:

By doing if(gabaritoVetor==notaVetor) , you are only comparing the reference of both vectors in memory, and as they are objects allocated in different spaces, the comparison will result in false and will not increment. See the example:

double vetor1[] = new double[3]; 
double vetor2[] = new double[3];

        System.out.print(vetor1 + " - " + vetor2);

Which returns something like this in ideone :

[D@106d69c – [D@52e922

To compare the values, you can iterate between the indices of the two vectors using loop loop (as shown in @WeslleyTavares' answer), or using the Arrays class:

 if(Arrays.equals(vetor1,vetor2)){
            System.out.println("vetor1  e vetor2 iguais");
        }else{
            System.out.print("vetor1  e vetor2 diferentes");
        }

See a complete comparison test using Arrays between vectors (equal and different) here on IDEONE

Note: note that the equals method compares the vectors pair by pair, and they will be equal if their references in memory are null, or if they have the same size, and have the same values ​​for the same pair of indices.

Scroll to Top