ComeçarComece de graça

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 exercício faz parte do curso

Optimizing Code in Java

Ver curso

Instruções do exercício

  • 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.

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

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 = ____;
        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;
    }
}
Editar e executar o código