List 构造函数中的检查列表是否存在重复项
我有一门课叫菜谱。配方不能包含重复的成分,否则将引发非法参数异常。我试图使用帮助列表,但我得到了一个行的NullPointerException:for int I=0;i.尺寸;我++List 构造函数中的检查列表是否存在重复项,list,duplicates,List,Duplicates,我有一门课叫菜谱。配方不能包含重复的成分,否则将引发非法参数异常。我试图使用帮助列表,但我得到了一个行的NullPointerException:for int I=0;i.尺寸;我++ public class Recipe { private String title; private String instructions; private LinkedList<Ingredient> ingredients; boolean nodupli
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;
}
}使用集合而不是列表,因为这是您想要的数据结构。简而言之,一个集合只包含唯一的元素。当你尝试添加已经存在的东西时,什么都不会发生。您必须重写Components类的equal/hash方法才能使其工作
我还尝试了构造函数中的一个集合,但也得到了一个NullPointerException