如何打印另一个类引用的所有对象

时间:2019-04-30 04:24:18

标签: java

我要打印引用对象phonebook1的“ Contato”类中的所有对象(不确定我是否正确输入了文字)

基本上我想打印该方法:

ListAllContacts(phonebook1);

  1. 鲍勃

  2. 玛丽

  3. 安娜

如果我将phonebook2作为参数:

ListAllContacts(phonebook2);

  1. 雅各布
public class Contato {
    public String nome;
    public String numero;
    public Agenda agenda;

    public Contato(String nome, String numero, Agenda agenda){
        this.nome = nome;
        this.numero = numero;
        this.agenda = agenda;   
    }
}

public class Agenda {
    public String nomeAgenda;

    public void ListAllContacts(Agenda agenda){
    }
}

public class AgendaTelefonica {
    public static void main(String[] args) {
        Agenda phonebook1 = new Agenda();
        Agenda phonebook2 = new Agenda();
        phonebook1.nomeAgenda = "phonebook1";
        phonebook2.nomeAgenda = "phonebook2";

        Contato c1 = new Contato("Bob", "123", phonebook1);
        Contato c2 = new Contato("Mary", "126", phonebook1);
        Contato c3 = new Contato("Ana", "568", phonebook1);
        Contato c4 = new Contato("Jacob", "998", phonebook2);       
    }   
}

1 个答案:

答案 0 :(得分:0)

您的结构是错误的和/或效率低下的。如果将对象放在Agenda类内的ArrayList中来访问对象会更好。这是一个示例:

public class Contato {
    public String nome;
    public String numero;
    public Agenda agenda;

    public Contato(String nome, String numero, Agenda agenda){
        this.nome = nome;
        this.numero = numero;
        this.agenda = agenda;
    }
}

public class Agenda {
    public String nomeAgenda;

    private ArrayList<Agenda> agendas;

    public Agenda() {
        agendas = new ArrayList<Agenda>();
    }

    public void ListAllContacts(){
        for (Agenda a : agendas) {
            System.out.println(a.nome);
        }
    }

    public void add(Agenda a) {
        agendas.add(a);
    }
}

public class AgendaTelefonica {
    public static void main(String[] args) {
        Agenda phonebook1 = new Agenda();
        Agenda phonebook2 = new Agenda();
        phonebook1.nomeAgenda = "phonebook1";
        phonebook2.nomeAgenda = "phonebook2";

        phonebook1.add(new Contato("Bob", "123", phonebook1));
        phonebook1.add(new Contato("Mary", "126", phonebook1));
        phonebook1.add(new Contato("Ana", "568", phonebook1));
        phonebook2.add(new Contato("Jacob", "998", phonebook2));       
    }   
}