实现一个联系人管理应用
您正在开发一个联系人管理应用,使用 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;
}
}