这是用于保留重复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);}


