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.
This exercise is part of the course
Optimizing Code in Java
Exercise instructions
- Use a for each loop to iterate through all contacts in the contacts list.
- Return the contact when the method finds it.
- Run the code as is (using the Run code button), then change
numberOfContacts
and run it again - how did the execution time change? Submit your code afterwards.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ContactManager manager = new ContactManager();
// Edit numberOfContacts to see how it affects execution time
int numberOfContacts = 10000;
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 (____) {
if (contact.getName().equals(name)) {
// Return the match
return ____;
}
}
return null;
}
}
class Contact {
private String name;
public Contact(String name) {
this.name = name;
}
public String getName() {
return name;
}
}