How do I access the indexes of a vector returned by a java method?

Asked

Viewed 621 times

4

I have a method called vetorVoos which returns a vector of the type NodeVoo and I want to access the indexes of this vector through the method in another class.

This is the method:

public NodeVoo[] vetorVoos(){
    if(isEmpty()){
        return null;
    }
    NodeVoo vetor[] = new NodeVoo[size()],aux2 = inicio;
    for (int i = 0; i < size(); i++) {
        vetor[i] = aux2;
        aux2 = aux2.proximo;
    }
    return vetor;
}

And I’ve tried to take the vector index in the following ways in another class:

vetorVoos()[1],
vetorVoos(1),
[1]vetorVoos()

None of it worked.

  • 2

    Are you sure that index 1 exists or the return was not null?

  • This example I used only, my problem is more in the syntax, because the program doesn’t even compile when I try to do so.

2 answers

2


First, stores the return of the function in a variable:
NodeVoo[] voos = vetorVoos();
and then access the indexes:
NodeVoo voo = voos[1];

  • Thank you, you got it right this way.

0

Create a class NodeVoo which will be your class template for a future list:

Nodevoo class (example)

public class NodeVoo {    
    private String descricao;
    public String getDescricao() {
        return descricao;
    }
    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }    
}

After the creation of the class NodeVoo create a list of Nodevoo (Array) by the name of ListaVoo as the code just below:

List flight class (example)

import java.util.ArrayList;
import java.util.List;
public class ListaVoo {
    public ListaVoo(){
        this.nodeVoo = new ArrayList<>();
    }    
    public ListaVoo(List<NodeVoo> nodeVoo){
        this.nodeVoo = nodeVoo;
    }
    private List<NodeVoo> nodeVoo;
    public List<NodeVoo> getNodeVoo() {
        return nodeVoo;
    }
    public void setNodeVoo(List<NodeVoo> nodeVoo) {
        this.nodeVoo = nodeVoo;
    }    
    public void addVoo(NodeVoo nodeVoo){
        this.nodeVoo.add(nodeVoo);
    }    
}

Using

    //Criando 2 instâncias da classe NodeVoo (Modelo)
    NodeVoo nodeVoo1 = new NodeVoo();
    NodeVoo nodeVoo2 = new NodeVoo();

    //Criando a lista de ListaVoo
    ListaVoo lista = new ListaVoo();

    //Adicionando na lista as duas classes NodeVoo
    lista.addVoo(nodeVoo1);
    lista.addVoo(nodeVoo2);

    //Resgatando a quantidade de itens na lista ListaVoo
    int quantidade = lista.getNodeVoo().size();

All relevant data are examples, but fully functional.

Browser other questions tagged

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