I'm trying to save different objects of the same class in an ArrayList, from an instance that is changing the value of the properties, I do not know if I explain. Here is a code that illustrates what I want to do.
Player Class:
package jugadores;
public class Jugador {
private String nombre;
private int puntuacion;
public Jugador() {}
public Jugador( String nombre, int puntuacion ) {
this.nombre = nombre;
this.puntuacion = puntuacion;
}
public String getNombre() {
return nombre;
}
public int getPuntuacion() {
return puntuacion;
}
public void setNombre( String nombre ) {
this.nombre = nombre;
}
public void setPuntuacion( int puntuacion ) {
this.puntuacion = puntuacion;
}
} //class
Main Class:
package jugadores;
import java.util.ArrayList;
import java.util.List;
public class Main {
private static String player1 = "Pepe";
private static String player2 = "Leo";
private static int score_player1 = 100;
private static int score_player2 = 92;
private static Jugador player;
private static List<Jugador> players_list = new ArrayList();
public static void main( String[] args ) {
//Jugador 1
player = new Jugador( player1, score_player1 );
players_list.add( player );
//Jugador 2
player.setNombre( player2 );
player.setPuntuacion( score_player2 );
players_list.add( player );
test();
}
private static void test() {
int size = players_list.size();
for ( int x = 0; x < size; x++ ) {
player = players_list.get( x );
tracePlayer( player );
}
}
private static void tracePlayer( Jugador x ) {
System.out.println( x.getNombre( ));
System.out.println( x.getPuntuacion( ));
System.out.println( "------------------" );
}
} //class
When this is executed, what I want is for you to print the data of player 1, and then the data of player 2, that is to say that in the ArrayList one player is saved first and then the other, and it does not end up having copies of the last player saved.
To simplify, I only use two players, whose data I included in the Main class, but it has to work with a data source that will generate an unknown number of players. Since I do not know how many players there will be so I can not create an instance for each one.