1

//contacts class

package com.company;

public class Contacts {
    private String name;
    private String number;

    public Contacts(String name, String number) {
        this.name = name;
        this.number = number;
    }

    public  String getName() {
        return name;
    }

    public String getNumber() {
        return number;
    }
}


//class Phone
package com.company;

import java.rmi.StubNotFoundException;
import java.util.ArrayList;

public class Phone {
    private ArrayList<Contacts> contacts1 = new ArrayList<Contacts>();


    public void addContact(String name, String numbers) {
        Contacts contacts = new Contacts(name, numbers);
        contacts1.add(contacts);

    }

    public void printContacts() {
        for (int i = 0; i < contacts1.size(); i++) {
            System.out.println(contacts1.); // >>> how to print elements (name and phone number)

        }
    }
}

Here I tried to print a list of contacts including name and phone number but could not handle how to iterate over a list of objects. How can I print name and phoneNumber using printContacts() method in Phone class? Thanks

  • have your IDE generate a `toString` method for the `Contacts` class and then use `System.out.println(contacts1);`. I would also suggest you rename `Contacts` (plural) to `Contact`. – f1sh Feb 13 '20 at 14:36
  • You need to override `toString()` in `Contacts` and in `for` print `contacts1.get(i).toString()` – KunLun Feb 13 '20 at 14:39

2 Answers2

1

You would do:

System.out.println(contacts1.get(i));

but that would just give Contacts@somenumber, so you will need to add a toString() method to the Contacts class. In the contacts class, add a function that looks like this:

@Override
public String toString() {
    return name + ": " + number;
}
1

Override toString method in your class Contacts to return a string representation of your class object (for e.g. json string). System.out.println prints string returned by this method.

public class Contacts {
  private String name;
  private String number;

  ...

  @Override
  public String toString() {
    return "{\"name\": \"" + name + "\", \"number\": \"" + number + "\"}";
  }
}

P.S. If you are using one the java IDEs, check out the implementation of println method in file PrintStream.java in java source code. Java IDEs provides this feature of code navigation in your project by which you can actually navigate through source code of Java itself.

mejariamol
  • 78
  • 5