If you really want to use an array, the way is for you to control the position where the next one should be inserted (taking care not to oversize the array). Something like that:
public class Teste {
private String lista[] = new String[2];
private int adicionados = 0; // conta quantos foram adicionados
public void adicionar(String nome) {
if (this.adicionados == this.lista.length) { // já lotou o array
System.out.println("não é possível adicionar mais nomes");
} else { // ainda tem espaço
this.lista[this.adicionados] = nome;
this.adicionados++;
}
}
public void mostrar() {
for (int i = 0; i < this.adicionados; i++) {
System.out.println("Nome " + this.lista[i]);
}
}
}
So you don’t need to make one loop to insert (looking for some space, until finding, as suggested to another answer), Just put your name in the right position. It’s okay that in this case the array is small, but for larger arrays this becomes impractical (and why go through everything again if I already know that the first positions will be occupied? doesn’t make sense).
The difference is that to show, you can’t do the loop throughout the array, and yes to the amount of names that have been entered. So you avoid printing a lot of null
(when initializing the array with new String[2]
, his values are set to null
).
That being said, if you want to add "free" names, without worrying about the size, you can use a list:
public class Teste {
private List<String> lista = new ArrayList<>();
public void adicionar(String nome) {
this.lista.add(nome);
}
public void mostrar() {
for (String nome : this.lista) {
System.out.println("Nome: " + nome);
}
}
}
Or, if you want to limit the maximum number of names you can have on the list:
public void adicionar(String nome) {
if (this.lista.size() == 10) { // supondo que só pode ter 10 no máximo
System.out.println("não é possível adicionar mais nomes");
} else { // ainda tem espaço
this.lista.add(nome);
}
}
The other answer suggested to use LinkedHashSet
, which also works. The difference is that the Set
does not allow repeated elements, while the List
allows (see what makes the most sense for your case).
The method
adicionar
always changes the value of all array elements...– hkotsubo
In the method
adicionar()
herefor (int i = 0; i < lista.length; i++) {lista[i] = nome;}
you are instructing that first element oflista
to the last receivenome
. Use a Arraylist in place of Array.– Augusto Vasques