實作聯絡人管理應用程式
你正在開發一個使用 ArrayList 維護使用者聯絡人清單的聯絡人管理應用程式。你需要實作並分析搜尋函式的效能,判斷當聯絡人數量增加時,是否仍能良好擴充。
本練習屬於課程
Java 程式碼最佳化
練習說明
- 將
numberOfContacts設為1000。 - 使用 for-each 迴圈逐一走訪
contacts清單中的每個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;
}
}