如何在数组列表中添加对象的属性?



我试图使用for循环将我的对象(存储在数组列表中)的特定属性添加在一起。我对它进行了测试,由于某种原因,只有一个对象被重复调用。我所指的方法是getCostOfRun()。有更多的代码,如果你需要更多的上下文,请询问。

import java.util.ArrayList;                                             
import java.util.Arrays;                                                
public class Phone                                              
{                                               
private static String Brand;                                                
private static String Type;                                             
private static String Model;                                                
private static String UniqueID;                                             
private static int ManufCost;                                               
public static ArrayList<Phone> Phones = new ArrayList<Phone>();                                             
public static int counter;                                              

public Phone(String Brand, String Type, String Model, String UniqueID, int ManufCost)                                               
{                                               
this.Brand=Brand;                                               
this.Type=Type;                                             
this.Model=Model;                                               
this.UniqueID=UniqueID;                                             
this.ManufCost=ManufCost;                                               
Phones.add(this);                                               
counter =counter +1;                                                
System.out.println(counter);                                                
}
public static int getCostOfRun()                                                
{                                               
int TotalCost=0;                                                
int tempcost=0;                                             
int count=0;                                                

while (Phones.size() > count) {                                                
tempcost=Phones.get(count).ManufCost;                                                
System.out.println(tempcost);                                                
TotalCost=TotalCost+tempcost;                                                
System.out.println(TotalCost);                                               
count++;                                             
}                                             
return TotalCost;                                               
}                                               

对于Java 8流,您可以使用

int totalCost = Arrays.stream(Phones).map(p -> p.manfCost).reduce(0, Integer::sum);