How to walk a [closed] arraylist

0

How to traverse an arraylist as long as it does not find the element and if at the end this element is not added to the lsita

    
asked by Elena Quintana 23.03.2018 в 14:46
source

2 answers

2

To be able to do it this way, it is not necessary to cross it, you can use the function contains :

if (!myArray.contains(elemento)) { //si tu arraylist no contiene el elemento
   myArray.add(elemento);
}
    
answered by 23.03.2018 в 14:53
0

There is a method called contains to be able to compare:

Arrays.asList(array).contains(elemento)

the example should look like this:

import java.util.Arrays;

public class MyClass {
    public static void main(String args[]) {

        int [] arr = {1,2,3,4,5,6};
        int comparador = 7;
        if (!Arrays.asList(arr).contains(comparador)){ //validamos si el elemento esta en la lista
            arr[arr.length - 1] = comparador; // Agregamos el elemento
        }
        System.out.println(Arrays.toString(arr));
    }
}
    
answered by 23.03.2018 в 15:37