查找 ArrayList 索引的方法,将对象添加到其中



我有一个ArrayList,它正在使用Customer类填充客户信息。在我的addCustomerRecord方法中,我在addCustomerRecord方法中调用findAddIndex,因此输入的数据将在显示数据之前进行排序。这是我的代码,不介意fileWhatever方法,我不使用它。

public class CustomerDemo
{
    //arrayList of customer objects
    public static ArrayList<Customer> customerAL = new ArrayList<>();

    public static void main (String[] args)
    {        
        //to hold menu choice
        String menuChoice = "";
        Scanner kb = new Scanner(System.in);
        System.out.println("To add a record press 'A': n"
                + "to display all records press 'D': n"
                + "to exit press 'Q': n");
        //loop priming read
        menuChoice = kb.nextLine();
        //make input case insensitive
        menuChoice = menuChoice.toLowerCase();

        do
        {
            if(menuChoice.equals("a"))
                addCustomerRecord(kb);
            else if(menuChoice.equals("d"))
            {
                displayCustomerRecords();
            }
            else if(menuChoice.equals("q"))
            {
                System.out.println("Program exiting..");
                System.exit(0);
            }
            else
            {
                System.out.println("incorrect entry. Please re-enter a valid entry: n");
                menuChoice = kb.nextLine();
                menuChoice = menuChoice.toLowerCase();
            }
            System.out.println("To add a record press 'A': n"
                    + "to display all records press 'D': n"
                    + "to exit press 'Q': n");
            menuChoice = kb.nextLine();
            menuChoice = menuChoice.toLowerCase();
        }while(menuChoice.equals("a") || menuChoice.equals("d") || menuChoice.equals("q"));

        kb.close();
    }
   /*     public static void displayCustomerRecords()
    {
        System.out.println();
        for (int i = 0; i < customerAL.size(); ++i)
        {
            System.out.printf("%-15s", customerAL.get(i).getLastName());
            System.out.printf("%-15s", customerAL.get(i).getFirstName());
            System.out.printf("%-6s", customerAL.get(i).getCustID());
            System.out.printf("%15sn", customerAL.get(i).getPhoneNumber());
        }
        System.out.println();
    }

    /**
     * prompts to enter customer data and mutator methods called 
     * with a Scanner object passed as an argument to set data
     * @param location index position of where the element will be added. 
     * @param kb a Scanner object to accept input
     */
    public static void addCustomerRecord(Scanner kb)
    {
        Customer currentCustomerMemoryAddress = new Customer();
        System.out.println("Enter first name: n");
        String fName = kb.nextLine();
        currentCustomerMemoryAddress.setFirstName(fName);
        System.out.println("Enter last name: n");
        String lName = kb.nextLine();
        currentCustomerMemoryAddress.setLastName(lName);
        System.out.println("Enter customer phone number: n");
        String pNum = kb.nextLine();
        currentCustomerMemoryAddress.setPhoneNumber(pNum);
        System.out.println("Enter customer ID number: n");
        String ID = kb.nextLine();
        currentCustomerMemoryAddress.setCustID(ID);
        int addLocation = findAddLocation(currentCustomerMemoryAddress);
        customerAL.add(addLocation, currentCustomerMemoryAddress);
        currentCustomerMemoryAddress = null;
    }
    public static int findAddLocation(Customer cust)
    {
        int location = 0;
        if(!customerAL.isEmpty())
        {
            for(int i = 0; i < customerAL.size(); i++)
            {
                //Stumped here
            }
        }
        else
            return location;
        return location;
    }
}    

看起来你正在重新发明轮子 威廉·

将用于displayCustomerRecords的代码替换为以下内容:

public static void displayCustomerRecords()
    {
        System.out.println();
        customerAL.stream().map(c -> String.format("%-15s%-15s%-6s%15sn",
                c.getLastName(), c.getFirstName(), c.getCustID(), c.getPhoneNumber()))
                .sorted()
                .forEach(System.out::print);
        System.out.println();
    }

更新

考虑到您的注释,您可以将findAddLocation方法替换为以下内容:

private static Comparator<Customer> comparator = Comparator.comparing(Customer::getLastName)
                .thenComparing(Customer::getFirstName)
                .thenComparing(Customer::getCustID)
                .thenComparing(Customer::getPhoneNumber);

public static int findAddLocation(Customer cust)
{
    int location = 0;
    if(!customerAL.isEmpty())
    {
        for(Customer customerInList : customerAL)
        {
            if(comparator.compare(customerInList, cust) > 0) {
                break;
            }
            location++;
        }
    }
    return location;
}

我们使用 Java 的增强型 for 循环遍历数组,并使用 Java 8 声明的比较器比较对象(我相信这是此分配的关键)。

如果您可以查看 Comparable 接口并在Customer类中实现它,那将是一个好主意。这样,您只需对customerInList.compareTo(cust)进行简单的调用即可比较这两个对象。

如前所述,这不是一个好的做法,不应该在生产代码中使用。

最新更新