我正在制作一本联系人书,它包含联系对象中保存的ArrayList中的联系人,但我想不出有办法访问地址簿中的联系人,有人可以帮帮我吗?我的代码片段如下:
//structure of each contact
public class Contact {
private String name;
private String cellNo;
private String email;
private String category;
}
//structure of the address book
public class AddressBook {
private ArrayList <Contact> contacts = new ArrayList<Contact>();
}
//Full AddressBook Class
import java.util.ArrayList;
public class AddressBook {
private ArrayList <Contact> contacts = new ArrayList<Contact>();
public AddressBook(ArrayList <Contact> contacts)
{
this.contacts = contacts;
public ArrayList<Contact> getContact() {
return contacts;
}
public void setContact(ArrayList<Contact> contacts) {
this.contacts = contacts;
}
public boolean addContact (Contact contact)
{
if(contact != null)
{
try{
contacts.add(contact);
return true;
}catch(NullPointerException e)
{
return false;
}
}
return false;
}
public boolean deleteContact(int index)
{
if(contacts != null)
{
contacts.remove(index);
return true;
}else {
}
return false;
}
public void viewSpecificContact(String number)
{
System.out.print("Search Results");
for(int i = 0; i < contacts.size(); i++)
{
if(contacts.get(i).getCellNo() == number)
{
System.out.println(contacts.get(i).getName());
System.out.println(contacts.get(i).getCellNo());
System.out.println(contacts.get(i).getEmail());
System.out.println(contacts.get(i).getCategory());
System.out.println("Contact Found");
}else{
System.out.println("Contact Not Found");
}
}
}
}
//full contact class
public class Contact {
private String name;
private String cellNo;
private String email;
private String category;
//Constructor
public Contact(String name, String cellNo, String email, String category)
{
this.name = name;
this.cellNo = cellNo;
this.email = email;
this.category = category;
}
//Setters and Getters
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getCellNo() {
return cellNo;
}
public void setCellNo(String cellNo) {
this.cellNo = cellNo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
//Printing Area
public void printName ()
{
System.out.print(getName());
}
public void printEmail()
{
System.out.print(getEmail());
}
public void printCellNo()
{
System.out.print(getCellNo());
}
public void printCategory()
{
System.out.print(getCategory());
}
}
答案 0 :(得分:2)
您编写了所需的方法!
public ArrayList<Contact> getContact() {
return contacts;
}
只需addressBookInstance.getContact()
。
作为旁注,我建议将方法重命名为getContacts
或getContactList
以明确。您将返回联系人列表,而不是单个联系人。