cs-320/ContactService.java
2023-12-06 18:37:58 -08:00

75 lines
2.0 KiB
Java

/*
Cody Cook
CS-320-H7022 Software Test Automation & QA 23EW2
2023/11/11
*/
import java.util.ArrayList;
import java.util.List;
public class ContactService {
private List<Contact> contacts;
public ContactService() {
// Initialize the list of contacts
this.contacts = new ArrayList<>();
}
public void addContact(Contact contact) {
// Check if a contact with the same ID already exists
if (getContactById(contact.getId()) != null) {
throw new IllegalArgumentException("Contact with the same ID already exists.");
}
// Add the contact to the list
contacts.add(contact);
}
public void deleteContact(String contactId) {
// Find and remove the contact with the specified contactId
boolean removed = contacts.removeIf(contact -> contact.getId().equals(contactId));
if (!removed) {
throw new IllegalArgumentException("Contact with ID " + contactId + " not found.");
}
}
public void updateContact(String contactId, String newFirstName, String newLastName, String newPhone,
String newAddress) {
// Find the contact by ID
Contact contactToUpdate = getContactById(contactId);
if (contactToUpdate == null) {
throw new IllegalArgumentException("Contact with ID " + contactId + " not found.");
}
// Update the contact's fields if new values are provided
if (newFirstName != null) {
contactToUpdate.setFirstName(newFirstName);
}
if (newLastName != null) {
contactToUpdate.setLastName(newLastName);
}
if (newPhone != null) {
contactToUpdate.setPhone(newPhone);
}
if (newAddress != null) {
contactToUpdate.setAddress(newAddress);
}
}
public Contact getContactById(String contactId) {
// Find and return the contact with the specified ID, or null if not found
for (Contact contact : contacts) {
if (contact.getId().equals(contactId)) {
return contact;
}
}
return null;
}
public List<Contact> getAllContacts() {
// Return a list of all contacts
return new ArrayList<>(contacts);
}
}