เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

สร้างแอปพลิเคชันจัดการรายชื่อผู้ติดต่อ

กำลังพัฒนาแอปพลิเคชันจัดการรายชื่อผู้ติดต่อ ซึ่งเก็บข้อมูลรายชื่อผู้ใช้ไว้ใน ArrayList โจทย์นี้ต้องการให้นำฟังก์ชันค้นหาไปใช้งาน จากนั้นวิเคราะห์ประสิทธิภาพเพื่อพิจารณาว่าฟังก์ชันนี้จะรองรับข้อมูลที่เพิ่มขึ้นได้ดีเพียงใด

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

การปรับแต่งโค้ดใน Java

ดูคอร์ส

คำแนะนำการฝึกหัด

  • กำหนด numberOfContacts เป็น 1000
  • ใช้ for each loop เพื่อวนซ้ำผ่านแต่ละ contact ใน contacts
  • Return ค่า contact เมื่อเมธอด findContact พบรายชื่อที่ต้องการ
  • รันโค้ดตามที่เป็นอยู่ (โดยใช้ปุ่ม Run code) จากนั้นเปลี่ยน numberOfContacts เป็น 10000 แล้วรันอีกครั้ง สังเกตว่าเวลาในการประมวลผลเปลี่ยนแปลงอย่างไร แล้วจึงส่งคำตอบ

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

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;
    }
}
แก้ไขและรันโค้ด