Doubt about changing data in java arrays

Asked

Viewed 403 times

1

I have an array of the Person class called vector.

I already populated the vector with instances of named persons of p1.

My question is how to change the value of p1 when you’re inside the array:

Example:

Person array called vector:

Pessoa p1 = new Pessoa();
vetor.add(p1);

To take the name for example would be:

vetor.get(posicao).getNome(); 

and works perfectly.

Now how do I set the name?

I tried to

vetor.set(posicao).setNome(); 

and it doesn’t work.

  • Could post how the array was created? you already tried vector.get(position). setName()?

1 answer

2

By your code it looks like you’re using a List, so you can do so:

The method get(<>) returns the linked object with its index:

//Criação da List
List<Pessoa> list = new ArrayList<>();

list.add(new Pessoa());

//Recupera o valor
Pessoa p1 = list.get(0);

//Altera o valor
p1.setNome("Novo nome.");

//Exibição do conteudo
list.forEach(p -> System.out.println(p.getNome()));

Browser other questions tagged

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