2012-09-01 57 views
0

我想爲兩個類中的每一個創建對象,並將這些對象的引用放置在arrayList中,然後迭代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()); 

回答

3

你可以添加他們像這樣:

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()); 
} 
0
  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英鎊每年