ComenzarEmpieza gratis

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.

Este ejercicio forma parte del curso

Optimizing Code in Java

Ver curso

Instrucciones del ejercicio

  • Set the numberOfContacts to 1000.
  • Use a for each loop to iterate through each contact in the contacts list.
  • Return the contact when the findContact method finds it.
  • Run the code as is (using the Run code button), then change numberOfContacts to 10000 and run it again, observing how the execution time change. Submit your answer afterwards.

Ejercicio interactivo práctico

Prueba este ejercicio y completa el código de muestra.

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;
    }
}
Editar y ejecutar código