Assemble a vector with 5 students, in the fifth student this vector multiplies by 2, being able to enter 10 [closed]

-4
private Aluno alunos[];
private int ultimaPosicao;
public int tam=5;
/**
 * Construtor 
 */
public VetorDeAlunos(){
    alunos = new Aluno[tam];
    ultimaPosicao = 0;
} 
/**
 * Metodo para inserir aluno na lista. Este metodo insere o aluno na ultima posiçao
 * disponivel
 * @params  Aluno aluno - Aluno a ser inserido no vetor.
 * 
 */
public void inserir(Aluno aluno){                
    //o array estoura aqui    
    this.alunos[ultimaPosicao] = aluno;
    ultimaPosicao++;        
}

// In this algorithm there are several other test classes for buttons and etc ... (MADE ON GREENFOOT)

    
asked by anonymous 23.03.2017 / 16:20

2 answers

0

Expanding the array size is impossible.

What you can do is reassign the variable alunos to a new large-dimension array based on old values using the copyOf() method of the java.util.Arrays class:

public void inserir(Aluno aluno){                
    //o array estoura aqui    
    this.alunos[ultimaPosicao] = aluno;
    ultimaPosicao++;
    if(ultimaPosicao == 5) {
        alunos = Arrays.copyOf(alunos, 10);
    }
}
    
23.03.2017 / 21:02
0

You have to get a% s of% s then

private Aluno alunosnovos[] = new Aluno[10];
alunosnovos = alunos;
alunos = alunosnovos;

Reason you have to increase the physical space copy the old ones to the new space and then copy back;

You need to make space grow before you try to add new elements or it does not work. Do you understand?

    
23.03.2017 / 16:32