【问题标题】:Pass References to Objects in Arraylist?传递对 Arraylist 中对象的引用?
【发布时间】:2012-09-01 15:46:30
【问题描述】:
我想为 2 个类中的每一个创建对象,并将对这些对象的引用放在 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());
【问题讨论】:
标签:
java
object
arraylist
【解决方案1】:
你可以像这样添加它们:
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());
}
【解决方案2】:
ArrayList<CarbonFootprint> myCarbonList = new ArrayList<CarbonFootprint>();
CarbonFootprint myCarbon1 = new Car(150332.00);
myCarbonList.add(myCarbon1);
CarbonFootprint myCarbon2 = new Car(13434.00);
myCarbonList.add(myCarbon2);
// Enhanced Loop to display the answer.
for (CarbonFootprint x : myCarbonList) {
System.out.printf("My Car emits %.2f pounds per year\n",
myCarbon1.getCarbonFootprint());
System.out.printf("My House produces %.2f pounds per year\n",
myCarbon2.getCarbonFootprint());
}
}
我的车每年排放 118762.28 磅
我的房子每年生产 10612.86 磅
我的车每年排放 118762.28 磅
我的房子每年生产 10612.86 磅