检查构造函数中的列表是否有重复项

时间:2013-12-15 13:49:21

标签: list duplicates

我有一个名为Recipe的课程。配方可能不包含重复的成分,否则应抛出非法参数异常。我尝试使用帮助列表但是我得到了一行的NullPointerException:“for(int i = 0; i< ingredients.size(); i ++)”

public class Recipe {

    private String title;
    private String instructions;
    private LinkedList<Ingredient> ingredients;

    boolean noduplicate = true;

    // constructor
    public Recipe(String title, String instructions,
            List<Ingredient> ingredients) {
        this.title = title;
        this.instructions = instructions;
        LinkedList<Ingredient> helplist = new LinkedList<Ingredient>();
        for (int i = 0; i < ingredients.size(); i++) {
            Ingredient x = ingredients.get(i);
            if (helplist.contains(x)) {
                noduplicate = false;
                throw new IllegalArgumentException(
                        "This ingredient is duplicate!");
            }
            if (noduplicate) {
                helplist.add(x);
            }
            noduplicate = true;
        }
        this.ingredients = helplist;

    }

}

1 个答案:

答案 0 :(得分:0)

使用集合而不是列表,因为这是您想要的数据结构。简而言之,集合仅包含唯一元素。当你尝试添加已经存在的东西时,没有任何反应。您必须覆盖您的Ingredients类的equal / hash方法才能使其正常工作。

http://docs.oracle.com/javase/7/docs/api/java/util/Set.html http://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html