up 0 down

Soy principiante en estudiante de programación Java. A continuación se muestra mi programa y estoy recibiendo ArrayIndexOutOfBoundsException cuales i tryed para solucionarlo y trabajado, pero ¿hay alguna manera mejor evitarlo.

Main.java

package com.example.java;

public class Main {
    public static void main(String[] args) {
        Product.initAll();
        for (int i = 0; i <Product.All().size() ; i++) {
            System.out.println(Product.get(i));
        }
    }
}

Product.java

package com.example.java;

public class Product extends ProductDB{
    private String mName;
    private String mDescription;
    private double mPrice;

    Product(String name, String description, double price) {
        mName = name;
        mDescription = description;
        mPrice = price;
    }

    private String getName() {
        return mName;
    }

    private String getDescription() {
        return mDescription;
    }

    private double getPrice() {
        return mPrice;
    }

    @Override
    public String toString() {
        return "mName=\""+ getName()+"\" mDescription=\""+ getDescription()+"\" mPrice=\""+ getPrice()+"\"";
    }
}

ProductDB.java

Traté de filtrar un índice con si la condición y funciona también. ¿pero hay alguna forma mejor sucinta de hacerlo en la propia clase ProductDB.

package com.example.java;

import java.util.ArrayList;
import java.util.List;

class ProductDB {
    private static List<Product> products;

    static void initAll() {
        products = new ArrayList<>();
        products.add(new Product("Chair","Sit on Chair",10.11));
        products.add(new Product("Table","Dance over Table",43.16));
        products.add(new Product("Camera","Pose like a model",43.16));
        products.add(new Product("SmartPhone","Pout for a selfie",43.16));
        products.add(new Product("Computer","Play video games",43.16));
        products.add(new Product("Bag","Pack clothes for trekking",43.16));
        products.add(new Product("Pot","Plant a beautiful Rose",43.16));
        products.add(new Product("Iron","Flatten your clothes without wrinkle",43.16));
        products.add(new Product("Password","Create a strong and weird password",43.16));
        products.add(new Product("Java","Practice 1 hour every day",43.16));
    }

    static List<Product> All() {
        return products;
    }
    //here
    static Product get(int index){
        if (index >= All().size() || index < 0) {
            System.out.println("Index range should be within range of 0 - "+(All().size()-1));
            System.exit(1);
        }
        return products.get(index);
    }
}