传递参考Arraylist中的对象?

时间:2012-09-01 15:46:30

标签: java object 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());

2 个答案:

答案 0 :(得分: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());
}

答案 1 :(得分: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磅

My House每年生产10612.86磅

我的汽车每年排放118762.28磅

My House每年生产10612.86磅