Create Array of Objects in java and access objects directly

1

So I need to do the following I have a class with some attributes and methods, I need to generate a array of objects of this class, however I wanted to be able to access them directly, currently what I could do is throw them in a arraylist and use get(posição) to assign them in a temporary variable to be able to access their methods and attributes.

Class to which I want to create an array of objects

public class BlocoView {
    private MemoriaTextField enderecoMemoria;
    private MemoriaTextField palavras;
    public BlocoView(boolean selected){
        if(selected){
            this.enderecoMemoria = new MemoriaTextField("0", true);
            this.palavras = new MemoriaTextField("???", true);
        }else{
            this.enderecoMemoria = new MemoriaTextField("0", false);
            this.palavras = new MemoriaTextField("???", false);            
        }
    }
    public MemoriaTextField getEndereco(){
        return this.enderecoMemoria;
    }
}

Class containing arraylist of above class objects

public class MemoriaView extends JPanel {
    private ArrayList listadeBlocos;
    public MemoriaView(){
        super();
        this.listadeBlocos = new ArrayList();
        this.listadeBlocos.add(new BlocoView(false));
        this.setLayout(new MigLayout());
        //Aqui que tenho que acessar os atributos ou metodos diretamente
        this.add(this.listadeBlocos.get(0));
    }

}

When trying to do something like

this.add(this.listadeBlocos.get(0).getEndereco);

java can not find the get address method

    
asked by anonymous 15.05.2014 / 15:42

1 answer

3

To do this you must set the generic type of ArrayList , like this:

public class MemoriaView extends JPanel {
    private ArrayList<BlocoView> listadeBlocos;
    public MemoriaView(){
        super();
        this.listadeBlocos = new ArrayList<BlocoView>();
        this.listadeBlocos.add(new BlocoView(false));
        this.setLayout(new MigLayout());
        //Aqui que tenho que acessar os atributos ou metodos diretamente
        this.add(this.listadeBlocos.get(0));
    }

}

Without this, the list type is set to Object and, even if the type instance you passed, will not have access to the methods directly.

Another alternative is to do a cast , like this:

BlocoView bloco = (BlocoView) this.listadeBlocos.get(0);
this.add(bloco.getEndereco());
    
15.05.2014 / 16:09