Assigning Arrays in Java

4

I own 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 want to assign just the repeated Strings without the Strings that do not repeat.

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);
    }
}

Assigning Arrays res = comparar; "copies" all array elements. How can I copy just the repeats?

    
asked by anonymous 16.07.2017 / 19:56

4 answers

3

You can simply 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);

Output:

  

Ana
Pedro

Based on this answer.

    
17.07.2017 / 13:29
2

How this feels like an exercise, there's only one idea for you. I believe that the algorithm you are looking for, using only arrays, is similar to:

  • [While Array1 has values) Get a x value of Array1 (you did it in the first for >)
  • [While Array2 has values] They get a value of Array2 (another for similar to the first) by comparing it with < strong> x and ...
    • A) If it is the same, add the value in the ArrayResult (your Array res).
    • B) If not, well, do nothing.
  • At the end of this computation, you should get the result you are looking for (which should be "Peter" and "Ana").

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

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

    My suggestion for you is to declare it this way:

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

    Doing this, even though all names in the Array names are in the Comparison Array, you will have no problems.

    Issue

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

    When we assign an Array to the other in Java, its values are not copied - which happens to be a copy of the Array's reference . After this operation, both variables effectively represent the same Array.

    For more information, this entry of Stackoverflow EN, can be useful (if there is a in PT that someone knows, edit). An example commented:

    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 copy needs, you should 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
    }
    
        
    16.07.2017 / 21:00
    0

    I modified your code and believe that 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 did not understand your question, please add a comment.

        
    16.07.2017 / 21:20
    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. See this modification and tell me what you think:

    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();
            }
    
        
    16.07.2017 / 22:50