我想为这两个类中的每一个创建对象,并将对这些对象的引用放入 arrayList<>,然后迭代 arrayList。
ArrayList<CarbonFootprint> myCarbon = new ArrayList<CarbonFootprint>();
我该如何实现它?我不需要 ArrayList 也能做到。
CarbonFootprint myCarbon = new Car(150332.00);
System.out.printf("My Car emits %.2f pounds per year\n",
myCarbon.getCarbonFootprint());
最佳答案
您可以像这样添加它们:
ArrayList<CarbonFootprint> myCarbonList = new ArrayList<CarbonFootprint>();
CarbonFootprint myCarbon1 = new Car(150332.00);
myCarbonList.add(myCarbon1);
CarbonFootprint myCarbon2 = new Car(13434.00);
myCarbonList.add(myCarbon2);
并显示:
for (CarbonFootprint footPrint: myCarbonList) {
System.out.printf("My Car emits %.2f pounds per year\n", footPrint.getCarbonFootprint());
}
关于java - 传递对 Arraylist 中对象的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12229171/