请参见以下说明:
第一版:
ArrayList<Tree> trees = new ArrayList<>();
for(Tree tree: trees) {
int amount = tree.calculate(tree.getLength(), tree.getLengthPrUnit());
ArrayList <Integer> amountMaterials = new ArrayList<>();
amountMaterials.add(amount);
request.setAttribute("amountMaterials", amountMaterials);
}
-
在此代码版本中,您试图创建新的
ArrayList
每次,如果你有更多
Tree
将创建多个ArrayList对象的对象。
-
request.setAttribute()
如果将此代码放在具有相同属性名称的循环中
amountMaterials
以前的值将被新值覆盖,最后只有一个值,即最后计算的值。
所以不建议使用第一个版本。
第二版:
ArrayList<Integer> amountMaterials = null;
ArrayList<Tree> trees = new ArrayList<>();
for(Tree tree: trees){
int amount = tree.calculate(tree.getLength(), tree.getLengthPrUnit());
amountMaterials.add(amount);
}
request.setAttribute("amountMaterials", amountMaterials);
在这里,您将在循环之外创建ArrayList对象,因此它将只创建一个实例,并且它将具有所有值和
要求setAttribute()
在循环之外,这意味着不会覆盖以前的值。
通过这个解释,您现在知道要使用哪个版本;)。