Java address book. How to prevent duplicate contacts in my code?

后端 未结 4 1083
执念已碎
执念已碎 2021-01-29 01:59
switch(menuChoice) {

case 1: 
    System.out.println(\"Enter your contact\'s first name:\\n\");
    String fname = scnr.next();
    System.out.println(\"Enter your cont         


        
4条回答
  •  借酒劲吻你
    2021-01-29 02:25

    You could simply use HashSet and avoid any kind of loops to test it. HashSet is in charge of this function.

    import java.util.Set;
    import java.util.HashSet;
    
    public class AddressBook {
    
       Set listOfContacts = new HashSet<>();
    
       public void addContact(Person p) {
          if (!listOfContacts.add(p))
             System.out.println("Sorry this contact already exists.");    
       }
    }            
    

    To increment ID property you should have 2 properties, 1 static and another one, and increment it in constructor. Look:

    public class Person {
       private final int ID;
       private static int id = 1000;
       private String fName;
       private String lName;
    
       public Person(String fName, String lName) {       // Constructor I'm using to try and increment the ID each time a Person object is created starting at 1001.
          this.ID= ++id;
          this.fName = fName;
          this.lName = lName;   
       } 
    

    To make the HashSet not accept duplicate objects you should set which properties should not be duplicated in the class (Person in your case). Follows an example:

       @Override
       public int hashCode() {
          int hash = 7;
          hash = 61 * hash + Objects.hashCode(this.fName);
          hash = 61 * hash + Objects.hashCode(this.lName);
          return hash;
       }
    
       @Override
       public boolean equals(Object obj) {
          if (obj == null || getClass() != obj.getClass())
             return false;
    
          final Person other = (Person) obj;
          if (!Objects.equals(this.fName, other.fName))
             return false;
    
          return Objects.equals(this.lName, other.lName);
       }
    }
    

    By the way, you can generate equals and hashCode methods using your IDE (Eclipse, NetBeans, etc.)

    EDIT

    Since you aren't able to use HashSet, I will show a version with ArrayList. By the way, you have to use HashCode and equals as I said to make it work well

    import java.util.List;
    import java.util.ArrayList;
    
    public class AddressBook {
    
       List arrayOfContacts = new ArrayList<>();
    
       public void addContact(Person p) {
          if (listOfContacts.contains(p))
             System.out.println("Sorry this contact already exists.");
    
          else
             arrayOfContacts.add(p);    
       }
    }
    

提交回复
热议问题