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