简体   繁体   中英

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?

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 . The first scenario will require additional rollback mechanism since object is already present in the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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