Doubt about changing data in arrays in java

1

I have an array of the Person class called vector.

I have already populated the vector with the instances of people named p1 .

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

Example:

Person Array named Vector:

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

To get the name for example would be:

vetor.get(posicao).getNome(); 

and works perfectly.

Now how do I set the name?

I tried

vetor.set(posicao).setNome(); 

and does not work.

    
asked by anonymous 08.06.2017 / 21:10

1 answer

2

For your code it looks like you're using a List, so you can do this:

The get (< >) method 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()));
    
08.06.2017 / 21:28