JLS
JLS

Reputation: 71

Prevent duplicates in arraylist

Can not figure out why this code doesn't prevent duplicate clients, duplicates are clients with the same name.

I know there is a better solution to this problem. But I'm just a beginner and want to solve this in a way like below. Thanks for help...

import java.util.*;

public class Kund { 


public static ArrayList<Kund> customerList = new ArrayList<>();


public static void addCustomer(){

System.out.println("Add a customer:");

String customerXName = Program.readString("Name of Customer: ");
String customerXAdress = Program.readString("Adress of Customer: ");

for (int index = 0; index < customerList.size(); index++) {
    Customer customerobj = customerList.get(index);

    if (customerobj.getName().equalsIgnoreCase(customerXName)) {
        System.out.println("Customer with the given name already exists.      Choose another name...");
        addCustomer();
        break;
    }
}

Customer customerX = new Customer(customerXName, customerXAdress);

customerList.add(customerX);

System.out.println("The following customer has been registered: "
        + customerX);
System.out.println(customerList);
System.out.println();

}

Upvotes: 0

Views: 120

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213193

You're using recursion there, and that's the issue. Once you find a name to be present in list, you again call addCustomer() method. In one of the call, where the name entered by user is not in list, you add it to the list, and return from the method.

After returning from last call, the control will reach to the stack of previous method call, where it continues to break from loop, and outside the loop, it adds the customer with the name and address of current stack, which is the duplicate one, but still gets added.

Call trace goes like this:

addCustomer() // name = "A", found duplicate
   addCustomer()  // name = "B", found duplicate
      addCustomer()  // name = "C", no duplicate.
      // add the customer with name = "C"
      // return to the previous call
   break the loop
   // outside the loop, add customer with name = "B" to the list
   // return to the previous call
break the loop
// outside the loop, add customer with name = "A" to the list

To solve the issue, you can return from the method instead of using break, or better use a loop instead.

Upvotes: 0

Eran
Eran

Reputation: 393771

If you enter a Customer that already exists in the list, the loop will find it and ask you to enter a new customer. However, after you enter a new customer, you don't restart the loop, so you don't check that the new customer you entered doesn't exist in the list.

In addition, it's not a good idea to call addCustomer recursively each time you find the customer already exists, since once the loop ends, the customer will be added.

Upvotes: 1

Related Questions