Assignment of Java Arrays

Asked

Viewed 806 times

4

I have two String Arrays and I have to compare them. After the comparison I must assign the repeated values in another Array. My problem is that I wish to assign only the Strings repeated without the repeating Strings.

Code:

//ARRAYS PARA COMPARAR:

String nomes[] = {"Pedro", "Diego", "Ana", "Carlos"};  
String comparar[] = {"Juliana", "Pedro", "Ana", "Luiz"};
String res[] = {};

//REALIZA A LEITURA DO ARRAY MAIOR:
for(String x : nomes){
    System.out.println("X : " + x);

    //SE HÁ STRING DO ARRAY MENOR NO MAIOR:
    if(nomes[0].equals(comparar[1])){
        //COPIA AS STRINGS PARA OUTRO ARRAY:
        res = comparar;       //***Problema***
    }

}

//MOSTRA AS STRINGS COPIADAS:
    for(String a : res){
        System.out.println("RES: " + a);
    }
}

The assignment of Arrays res = comparar; "copies" all elements of the array. How can I copy only the repeated?

  • 1

    I apologize for the editing errors and thank you very much for the amendments Denis Rudnei de Souza.

  • Thank you. About the editions that I made

  • Obs: If you wish to notify someone, you can put a @ in front of the name, so @Denis Rudnei de Souza

4 answers

3


You can just do:

String nomes[] = {"Pedro", "Diego", "Ana", "Carlos"};  
String comparar[] = {"Juliana", "Pedro", "Ana", "Luiz"};

Set<String> s1 = new HashSet<String>(Arrays.asList(nomes));
Set<String> s2 = new HashSet<String>(Arrays.asList(comparar));
s1.retainAll(s2);

String[] res = s1.toArray(new String[s1.size()]);

for(String r : res) 
    System.out.println(r);

Exit:

Ana
Pedro


Based in that reply.

  • 1

    With Guava Set<T> set = Sets.newHashSet(nomes);, in Java 8 Arrays.stream(nomes).collect(Collectors.toSet());

  • 1

    It worked perfectly Igor Venturelli. I will study more about Set and Hashset. Thank you very much!

  • @Alan.O.S cool! I’m glad I helped. If it worked, could you dial as solution, please?

  • 1

    I forgot to dial. Thanks again!

2

Since this looks like an exercise, there’s only one idea for you. I believe that the algorithm you seek, using only arrays, is similar to:

  1. [As the Array1 hold values] Get a value x of Array1 (you did it in the first for)
  2. [As the Array2 have values] Get a value of Array2 (another for similar to the first) comparing it with the value x and...
    • A) If equal, add the value in the Array (your Array res).
    • B) If not, well, do nothing.

At the end of this computation, you should get the search result (which should be "Pedro" and "Ana").

X : Pedro
X : Diego
X : Ana
X : Carlos
RES: Pedro
RES: Ana

One detail: take care with your result Array declaration String[] res = {}. When you declare an array this way, you are effectively creating an array with zero positions, which will cause you problems when trying to assign a value.

My suggestion to you is to declare this way:

String res[] = new String[nomes.length];

By doing this, even if all the names of the Array names are in the Comparison Array, you will have no problems.

Editing

Initially, I thought it would be better not to talk about it but, on second thought, I find it useful to leave here a comment regarding the "copy" of arrays (as mentioned in the question), for completeness.

When we assign an Array to another, in Java, its values are not copied - what happens is a copy of reference of the Array. After this operation, both variables effectively represent the same Array.

For more information, this Stackoverflow EN input, may be useful (if there is one in PT that someone knows, edit). A commented example:

public static void passagemDeReferencia() {
    String[] array1 = {"Pedro", "Diego", "Ana", "Carlos"};
    String[] array2 = array1; // Isto passa uma referência do Array - não é uma cópia

    // Ambos arrays são idênticos, conforme visto comparando a primeira posição.
    System.out.println("array1[0] == array2[0]: " + array1[0].equals(array2[0]));
    System.out.println("array1[0]: " + array1[0]);
    System.out.println("array2[0]: " + array2[0]);
    // array1[0] == array2[0]: true
    // array1[0]: Pedro
    // array2[0]: Pedro

    // Alterar qualquer posição do array2, irá alterar o array1.
    array2[0] = "Miguel"; 
    System.out.println("array1[0] == array2[0]: " + array1[0].equals(array2[0]));
    System.out.println("array1[0]: " + array1[0]);
    System.out.println("array2[0]: " + array2[0]);
    // array1[0] == array2[0]: true
    // array1[0]: Miguel
    // array2[0]: Miguel

    // Assim como alterar qualquer posição de array1, irá alterar o array2.
    array1[0] = "Pedro"; 
    System.out.println("array1[0] == array2[0]: " + array1[0].equals(array2[0]));
    System.out.println("array1[0]: " + array1[0]);
    System.out.println("array2[0]: " + array2[0]);
    // array1[0] == array2[0]: true
    // array1[0]: Pedro
    // array2[0]: Pedro
}

For copying needs, use an Array Copy.

public static void copiandoArrays() {
    String[] array1 = {"Pedro", "Diego", "Ana", "Carlos"};
    String[] array2 = new String[array1.length];
    System.arraycopy(array1, 0, array2, 0, array1.length); // Este método efetua uma cõpia do array
    // Mais código
}
  • I understand your logic for the Miguel code, I will implement it. Thank you for suggesting the Array Result statement. Many thanks Miguel Fontes!

0

I modified your code and I believe I found the solution:

String nomes[] = {"Pedro", "Diego", "Ana", "Carlos"};  
        String comparar[] = {"Juliana", "Pedro", "Ana", "Luiz"};
        ArrayList<String> res= new ArrayList<String>();

//REALIZA A LEITURA DO ARRAY MAIOR:
        for(int i = 0 ; i < nomes.length;i++){
            String nome=nomes[i];
            System.out.println("X : " + nome);

            //SE HÁ STRING DO ARRAY MENOR NO MAIOR:
            for(String y :comparar){
                if(y.equals(nome))
                {
                    res.add(nome);
                    Toast.makeText(getApplicationContext(),nome,Toast.LENGTH_LONG).show();
                }

              }}

If I don’t understand your question, please add a comment.

0

I realize that you updated your question and did not accept any Answer, which leads me to believe that you want the "result" to be an Array string not an Array List String. Look at this modification and tell me what you found:

String nomes[] = {"Pedro", "Diego", "Ana", "Carlos"};  
        String comparar[] = {"Juliana", "Pedro", "Ana", "Luiz"};
        String res[] = {};
        ArrayList<String> repetidos= new ArrayList<String>();

        //REALIZA A LEITURA DO ARRAY MAIOR:
        for (int i = 0 ; i < nomes.length;i++)
        {
            String nome=nomes[i];
            System.out.println("X : " + nome);

            //SE HÁ STRING DO ARRAY MENOR NO MAIOR:
            for (String y :comparar)
            {
                if (y.equals(nome))
                {
                    repetidos.add(nome);
                }
            }
        }

        //ADICIONA ARRAY LIST PARA ARRAY STRING
        res = new String[repetidos.size()];

        for (int i = 0;i < repetidos.size();i++)
        {
            res[i] = repetidos.get(i);
        }
        //MOSTRA AS STRINGS COPIADAS:
        for(String a : res){
            System.out.println("RES: " + a);
            Toast.makeText(getApplicationContext(),a+" Tamanho "+res.length,Toast.LENGTH_LONG).show();
        }
  • It worked perfectly Jefferson! It was very clear the reading and interpretation of your code. Thank you very much.

  • You’re welcome, I’m happy to help

Browser other questions tagged

You are not signed in. Login or sign up in order to post.