我正在做一个大学项目。阻止我几乎所有进展的主要问题之一是用arraylist内容填充设置器。 arraylist是object类型。 这是代码:
import java.util.ArrayList;
import java.util.List;
public class Whisky {
private String name;
private String description;
private int quantity;
public Whisky(String nm, String desc, int quant) {
this.name = nm;
this.description = desc;
this.quantity = quant;
List<Object> WhiskyList = new ArrayList<Object>() ;
WhiskyList.add("Balvenie");
WhiskyList.add("triple cask 12. Matured in the three most traditional types of cask – first-fill bourbon, refill bourbon and sherry");
WhiskyList.add(10);
WhiskyList.add("Glenfiddich");
WhiskyList.add("Reserve Cask. This Whisky has been matured exclusively in Spanish sherry casks");
WhiskyList.add(10);
WhiskyList.add("Laphroig");
WhiskyList.add("Laphroig Four Oak. Matured in four different types of cask: ex-bourbon barrels, small quarter casks, virgin American oak barrels and European oak hogsheads.");
WhiskyList.add(10);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity= quant;
}
}
因此,基本上我想做的是运行一个遍历arraylist.size()的for循环,并针对其执行的每个“步骤”,将内容放入正确的setter中。那可能吗?
答案 0 :(得分:1)
我认为您正在尝试建立威士忌酒实例的初始列表。有很多方法可以做到这一点。这是一个使用静态列表并使用静态方法填充它的方法(在类加载时运行一次)。
public class Whisky {
public static final List<Whisky> WhiskyList = new ArrayList<Whisky>();
static {
WhiskyList.add(new Whisky("Balvenie",
"triple cask 12. Matured in the three most traditional types of cask – first-fill bourbon, refill bourbon and sherry",
10));
WhiskyList.add(new Whisky("Glenfiddich",
"Reserve Cask. This Whisky has been matured exclusively in Spanish sherry casks",
10));
WhiskyList.add(new Whisky("Laphroig",
"Laphroig Four Oak. Matured in four different types of cask: ex-bourbon barrels, small quarter casks, virgin American oak barrels and European oak hogsheads.",
10));
}
private String name;
private String description;
private int quantity;
public Whisky(String nm, String desc, int quant) {
this.name = nm;
this.description = desc;
this.quantity = quant;
}
// finish with getters and settings
}
答案 1 :(得分:0)
您的类的构造函数应仅初始化该类的字段。 WhiskeyList
变量最有可能应采用main()
方法。但是在您这样做之前,我建议编写一个main()
来创建一个单独的Whiskey
实例。