类变量java中的数组之和

时间:2018-03-22 13:54:35

标签: java

我刚开始使用OOP java,我正在努力从数组中获取类类型元素的总和。谁能帮我? hwComponents是类HardwareComponent的列表类型。任何帮助将不胜感激。

private Collection<HardwareComponent> hwComponents = new ArrayList<>();
public float calculatePrice() 
{

float sum=0;
for (int i=1;i < hwComponents.size(); i++) 
    sum+= hwComponents.get(i); //The method get(i) is undefined for this type
    return sum;

}

2 个答案:

答案 0 :(得分:2)

Collection没有get(index)方法。

将您的ArrayList存储在List变量中:

private List<HardwareComponent> hwComponents = new ArrayList<>();

另请注意,循环的索引应从0开始。

作为替代方案,您可以使用增强型for循环,这不需要get方法:

for (HardwareComponent hc : hwComponents) {
    sum+= hc.getSomeProperty(); // note that HardwareComponent cannot be added to 
              // a float (or to anything else for that matter, so you probably
              // intended to call some method of your class which returns a float
}

答案 1 :(得分:0)

如果您不想更改数组/集合的类型,只需按集合定义的顺序遍历集合:

sum = 0;
for( HardwareComponent hc: hwComponents)
    sum += hc.cost;
return sum;