In JAVA "From the ArrayList that stores the elements of the class type, retrieve the data of the fields of each element in order" I didn't know how to define this process as a method. Write down the solution as a memorandum.
--I don't know how to specify ArrayList as a method parameter
**-> ** ʻArrayList 
--I don't know how to call a class field in a for statement
**-> ** List variable name.get (i) .getName () etc.
OpenJDK 13 (Using dokojava)
With source code that imitates a vending machine system, --Main.java (Class containing Main method and the method in question this time) --Drink.java (class showing drinks)
It consists of two files.
Main.java
import java.util.ArrayList;
public class Main {
	public static void main(String[] args) {
        var drinklist = new ArrayList<Drink>();
        //Add drink to ArrayList that stores Drink class
        Drink coffee = new Drink("coffee", 1, 130);
        drinklist.add(coffee);
        Drink water = new Drink("water", 2, 100);
        drinklist.add(water);
        //Calling the method in question this time
        displayProduct(drinklist);
        }
        //Define method
        //Extract the fields of Drink class from ArrayList in order
    public static void displayProduct(ArrayList<Drink> drinklist) {
        for(Drink drink : drinklist) {
        System.out.println(drink.getNumber() + "." + drink.getName()
            + drink.getPrice() + "Circle");
        }
    }
}
Drink.java
public class Drink {
    private String name;
    private int number;
    private int price;
    
    public String getName() {
    return this.name;
    }
    public int getNumber() {
        return this.number;
    }
    public int getPrice() {
        return this.price;
    }
    
    public Drink(String name, int number, int price){
        this.name = name;
        this.number = number;
        this.price = price;
    }
}
Output result
1.Coffee 130 yen
2.Water 100 yen
        Recommended Posts