2012-09-01 31 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英镑每年