1

I just want to have a kind of master ArrayList that a user can add elements to (easy enough), but for each one of those elements, I want the user to be able to view another ArrayList specific for that element.

As an example, it could be like a custom recipe book - The user adds the name of a meal, and when they select that meal they can view/amend the ingredients required for that meal.

The idea seems pretty straight forward, but I can't find a solution that allows a dynamic list and each item on that list to have another dynamic list.

1
  • Does this differ at all from a List<List<Ingredient>>, for example? Commented May 10, 2016 at 19:27

2 Answers 2

3

What I'm going to show is my opinion of a nice design, though know that there are a lot of ways to approach this.

Your master list:

List<Meal> meals = new ArrayList<>();

Now Meal is a class which holds a list of Ingredient, and hell, let's give the meal a name!

public class Meal{
    private List<Ingredient> ingredients = new ArrayList<>();
    private String name;

    //getters, setters, constructor if you will
}

Your `Ingredient is then a simple class consisting of whatever you want, for example:

public class Ingredient{
    private String name;
    private String grams;

    //getters, setters, constructor if you will
}

Depending on what it is you want, this should suffice, you can work with interfaces or super classes if you want to be more flexible as well.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, that works a treat on the testing I've done here. Thanks very much Roel!
0

I like Roels method and it is the most expandable but here is another way if you dont want to create new classes. have a hashmap of strings to an arraylist of strings.

HashMap meals = new HashMap<String,ArrayList<String>>();
ArrayList<String> ingredients = new ArrayList();
ingredients.add("potatoes");
ingredients.add("butter");

meals.put("mashed potatoes",ingredients);

1 Comment

Nice and simple, thanks. I've found a nice use for this for another project I'm working on :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.