Greetings friends. I started learning Java not so long ago and would appreciate some help.
I have a Person class with the variables firstName , secondName and lastName .
There is a class AdressBook in which ArrayList<Person> . In this sheet I add 3 Person 's.
There is also an addPerson method that simply adds a new Person to the collection.
I need to supplement this method so that before adding it is checked: is there a Person with such a full name ( firstName , secondName and lastName ) or not.
Help to implement the method correctly. Unfortunately, my check fails, and the cycle in which I iterate over the collection does not end. Surely children's mistakes, but nonetheless ++ you in karma).
public class Main { public static void main(String[] args) { AdressBook contact = new AdressBook(); Adress a1 = new Adress("Russia", "Voronezhskaya obl.", "Voronezh", "Prospekt Truda", "2B", 394006, "31"); Adress a2 = new Adress("Russia", "Moskovskaya obl.", "Korolev", "Prospekt Kosmonavtov", "8A", 632008, "35/2"); Adress a3 = new Adress("Israel", "Tel-aviv.", "Petah Tikva", "Shpritsek", "14", 123478, "12"); Person p1 = new Person("Ivan", "Ivanovich", "Ivanov", 15, true, "89155473197", a1); Person p2 = new Person("Petr", "Petrovich", "Petrov", 59, true, "89998217516", a2); Person p3 = new Person("Sidor", "Sidorovich", "Sidorov", 27, true, "85241325698", a3); contact.book.add(p1); contact.book.add(p2); contact.book.add(p3); contact.addPerson2(p1); } } public class AdressBook { public ArrayList<Person> book = new ArrayList<>(); public void addPerson2(Person person) { for (int i = 0; i < book.size();i++ ) { if (person.firstName.equals(book.get(i).firstName) && person.secondName.equals(book.get(i).lastName) && person.lastName.equals(book.get(i).lastName)){ System.out.println("Такой контакт уже существует."); } else { book.add(person); } } } public class Person { String firstName; String secondName; String lastName; int age; boolean gender; String phone; Adress ad; public Person(String firstName, String secondName, String lastName, int age, boolean gender, String phone, Adress ad) { this.firstName = firstName; this.secondName = secondName; this.lastName = lastName; this.age = age; this.gender = gender; this.phone = phone; this.ad = ad; } }