1

Hello again stackoverflow, I have a question concerning List of Objects.

I have tried out writing some things, but can't find it though. How do I find an Object in a list of objects, when these objects are lists of its own?

this is what i have so far:

Recipe is a List of: {modification[], ingredients[], recipeBookName, recipeName}

public void removeFromBook(Recipe recipeName) {
    recipes = getRecipes();
    emptyRecipe = getEmptyPage(recipeBookName);

Now, I want to replace a Recipe which has a recipeName, by the emptyRecipe. I think it will be something like:

for(r in recipes) {
    if(r.recipeName == recipeName) {
        list.replace(Recipe, emptyRecipe)
    } else {

    }
}

any ideas? :)

here's my constructor for the Recipe class:

    public String[] modifications;
public String[] ingredients;
public String recipeName;
public String partOfRecipeBook;

public Recipe(String recipeName, String[] modifications, String[] ingredients, String recipeBookName){
    setRecipeModifications(modifications);
    setRecipeIngredients(ingredients);
    setRecipeName(recipeName);
    setRecipeBookName(recipeBookName);
}

Your approach looks fine, except that you should compare strings with equals:

if(r.recipeName.equals(recipeName)) {

Now an even easier way would be to store your recipes in a Map:

Map<String, Recipe> recipes = new HashMap<String, Recipe>();
recipes.put("Pizza with Lobster", new Recipe());

when you want to replace a recipe:

recipes.put("Pizza with Lobster", emptyRecipe);

and the old recipe has been replaced.

4

2 回答 2

2

Using a List with Objects in it (of which some are arrays) is not the best way it would be better to define a new object Recipe and use that.

public class Recipe {
    private List<Ingredient> ingredients;
    private List<Modification> modifications;
    private String bookName;
    private String book;
}

Then replacing in ingredients is a lot simpler. e.g. give recipe a function like

public void replaceIngredent(Ingredient oldIngredient, Ingredient newIngredient) {
    int index = ingredients.indexOf(oldIngredient);
    if (index != -1) {
        ingredients.remove(index);
        ingredients.add(index, newIngredient);
    }
}
于 2012-05-15T14:10:18.563 回答
2

您的方法看起来不错,除了您应该将字符串与等号进行比较:

if(r.recipeName.equals(recipeName)) {

现在更简单的方法是将您的食谱存储在地图中:

Map<String, Recipe> recipes = new HashMap<String, Recipe>();
recipes.put("Pizza with Lobster", new Recipe());

当您想替换配方时:

recipes.put("Pizza with Lobster", emptyRecipe);

旧配方已被替换。

于 2012-05-15T14:05:28.810 回答