MulaiMulai sekarang secara 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.

Latihan ini adalah bagian dari kursus

Optimizing Code in Java

Lihat Kursus

Petunjuk latihan

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

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

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;
    }
}
Edit dan Jalankan Kode