Implementing a contacts management application
You're developing a contacts management application that maintains a list of user contacts using an ArrayList. You need to implement and then analyze the performance of your search function to determine if it will scale well as the number of contacts grows.
Diese Übung ist Teil des Kurses
Optimizing Code in Java
Anleitung zur Übung
- Set the
numberOfContactsto1000. - Use a for each loop to iterate through each
contactin thecontactslist. - Return the contact when the
findContactmethod finds it. - Run the code as is (using the Run code button), then change
numberOfContactsto10000and run it again, observing how the execution time change. Submit your answer afterwards.
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
public class Main {
public static void main(String[] args) {
ContactManager manager = new ContactManager();
// Edit numberOfContacts to see how it affects execution time
int numberOfContacts = ____;
for (int i = 0; i < numberOfContacts; i++) {
manager.addContact(new Contact("Contact_" + i));
}
Contact result = manager.findContact("Contact_" + (numberOfContacts - 1));
System.out.println("Found: " + result.getName());
}
}
public class ContactManager {
private ArrayList contacts;
public ContactManager() {
contacts = new ArrayList<>();
}
public void addContact(Contact contact) {
contacts.add(contact);
}
public Contact findContact(String name) {
// Complete loop to search through contacts
for (Contact ____ : ____) {
if (contact.getName().equals(name)) {
// Return the match
return ____;
}
}
return null;
}
}