Java地址簿。如何防止代码中重复的联系人?

Java地址簿。如何防止代码中重复的联系人?,第1张

Java地址簿。如何防止代码重复的联系人?

这是用于保留重复ID的代码。

public void addContact(Person p) {    for(int i = 0;  i < ArrayOfContacts.size(); i++) {        Person contact = ArrayOfContacts.get(i);        if(contact.getID() == p.getID()) { System.out.println("Sorry this contact already exists."); return; // the id exists, so we exit the method.         }    }    // Otherwise... you've checked all the elements, and have not found a duplicate    ArrayOfContacts.add(p);}

如果您想更改此代码以保留重复的名称,请执行以下 *** 作

public void addContact(Person p) {    String pName = p.getFname() + p.getLname();    for(int i = 0;  i < ArrayOfContacts.size(); i++) {        Person contact = ArrayOfContacts.get(i);        String contactName =  contact.getFname() + contact.getLname();         if(contactName.equals(pName)) { System.out.println("Sorry this contact already exists."); return; // the name exists, so we exit the method.         }    }    // Otherwise... you've checked all the elements, and have not found a duplicate    ArrayOfContacts.add(p);}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5016943.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-14
下一篇2022-11-15

发表评论

登录后才能评论

评论列表(0条)

    保存