防止arraylist重复

时间:2015-03-31 11:21:44

标签: java arraylist duplicates

无法弄清楚为什么此代码不会阻止重复的客户端,重复的是具有相同名称的客户端。

我知道这个问题有更好的解决方案。但我只是一个初学者,并希望以下面的方式解决这个问题。谢谢你的帮助...

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();

}

2 个答案:

答案 0 :(得分:1)

如果您输入列表中已存在的客户,则循环将找到该客户并要求您输入新客户。但是,在您输入新客户后,您不会重新启动循环,因此您不会检查列表中是否存在您输入的新客户。

此外,每次发现客户已经存在时,递归调用addCustomer并不是一个好主意,因为一旦循环结束,客户就会被添加。

答案 1 :(得分:0)

你在那里使用递归,这就是问题所在。找到列表中的名称后,再次调用addCustomer()方法。在其中一个调用中,用户输入的名称不在列表中,您将其添加到列表中,然后从该方法返回。

从最后一次调用返回后,控件将到达先前方法调用的堆栈,从循环继续break,在循环外,它向客户添加当前堆栈的名称和地址,这是重复的,但仍然会被添加。

呼叫追踪如下:

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

要解决此问题,您可以从方法中return而不是使用break,或者更好地使用循环。