简体   繁体   English

循环内的 ArrayList

[英]ArrayList inside a loop

My question is can I do the same thing with ArrayList which is asking the user to input name and price and access the object member and set the name and price or I must create the object first and pass it to the ArrayList?我的问题是我可以对 ArrayList 做同样的事情,它要求用户输入名称和价格并访问对象成员并设置名称和价格,或者我必须先创建对象并将其传递给 ArrayList?

public static void startMethod(Item[] itemsList, Scanner keyBoard){
    for (int i = 0; i < itemsList.length; i++) { // for loop iterate 3 times
        itemsList[i] = new Item(); // Create new object every time the loop iterate
        System.out.println("Enter an item's name");
        itemsList[i].setName(keyBoard.nextLine());
        System.out.println("Enter an item's price");
        itemsList[i].setPrice(keyBoard.nextDouble());
        keyBoard.nextLine();// To avoid the skip line that is done by the nextLine() method
    }

or do I need to create the object first and pass the whole object?还是我需要先创建对象并传递整个对象? example例子

System.out.println("Enter a name");
    String input = key.nextLine();
    System.out.println("Enter a price");
    double x = key.nextDouble();
    Item itemList1 = new Item(input,x);
    itemsList.add(itemList1);

Second scenario is definitively better, more maintainable and probably easier to debug.第二种方案绝对更好、更易于维护并且可能更容易调试。

Moreover, most importantly, it will behave much better in the scenario when you encounter an exception when constructing your object - Item .此外,最重要的是,当您在构造对象 - Item时遇到异常时,它会在场景中表现得更好。 The first scenario will require additional rollback mechanism since object is already present in the array.第一种情况需要额外的回滚机制,因为对象已经存在于数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM