How to use Vectors for Instacing in JAVA?

Asked

Viewed 58 times

-1

Hello, I’m doing a game of questions and answers in java and I’m having problems with the instacing of Multiplus players(Object).

I wonder how it is possible to use vectors to create Multiplus players (Objects), how to access and modify the values of attributes present in the class. Could someone give me that light?

2 answers

1

Good afternoon Herbet,

You could create a array with the type of class representing the player and go saving in it

Player[] players = new Player[100];
         players[0] = player;

To retrieve/modify objects you will need to know the position the object is in, which is already a problem, and access the properties of the object as follows

long scores = players[0].getScores();
              player[10].setLife(10);

// Outra forma com variáveis
Player player45 = player[45];
       player45.setDecreaseslife(34);

Imagine that you have no idea what position the player is in, to find it you could do something like

for(int i = 0; i < players.lenght; i++) {
    /* Compare uma informação previamente conhecida */
}

But that’s not so scalable, imagine you have one array 2000 players... But it is logical that these details are related to each project.

We also have the problem from the beginning: the dimensioning. In Java, arrays are immutable structures. This means in practice that if you define your array with n positions, and happen of only a much smaller amount than n of objects occupying the array, you will have an object in memory with a size that it truly does not need. Or it may also happen otherwise, where you define n positions and try to save in a position outside the range of n [the size of array is from 0 to n-1 in Java], then prepare to receive an error stating that there is no more space. One option would be to copy the arrayto another and increase the size, which probably won’t be cool for performance. I advise you to study another structure, see the list types available in Java and choose the one that best fits your problem.

0

The friend used array, I’d use a list, growth occurs according to need, in case it was just doing something similar to that:

ArrayList<Jogadores> jogadores = new ArrayList<Jogador>();
Jogador j1 = new Jogador();
jogadores.add(j1);
// faz a sua manipulação
jogadores.get(0).getPontuacao();
// caso queira andar pelo array
for(Jogador j : jogadores) {
// faça sua manipulação com todos os jogadores...
}

Browser other questions tagged

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