简体   繁体   中英

(Simple) Add different types to ArrayList <class>

So I need to get the int and the boolean into the contractor so I can calculate different things through methods. Is there a way I could do this through an ArrayList, or two. I just need help getting it there! Thank you for any help.

Main Method:

import java.util.ArrayList;
public class Tester
{
public static void main(String[] args)
{
   ArrayList<Contructor> cO2 = new ArrayList<Constructor>();
       // add households to the arraylist
       CO2FromWaste homeData = new CO2FromWaste();
       cO2.add();

   for(Contructor dataRecord : cO2)
   {
       dataRecord.calcGrossWasteEmission();
       dataRecord.calcWasteReduction();
       dataRecord.calcNetWasteReduction();
   }

Constructor:

public class Contructor
{
private int myNumPeople;
private boolean myPaper, myPlastic, myGlass, myCans;
private double myEmissions, myReduction, myNetEmissions;

/**
* Constructor for objects of type CO2FromWaste
* @param numPeople number of people in a household
* @param paper whether or not paper is recycled
* @param plastic whether or not plastic is recycled
* @param glass whether or not glass is recycled
* @param cans whether or not cans are recycled
*/
Contructor(int numPeople, boolean paper, boolean plastic, boolean glass, boolean cans)
{
   myNumPeople = numPeople;
   myPaper = paper;
   myPlastic = plastic;
   myGlass = glass;
   myCans = cans;
   myEmissions = 0.0;
   myReduction = 0.0;
   myNetEmissions = 0.0;
 }

You were almost there. The ArrayList#add method takes an Object as parameter. In this case, your Object is a CO2FromWaste .

ArrayList<CO2FromWaste> cO2 = new ArrayList<CO2FromWaste>();
CO2FromWaste homeData = new CO2FromWaste();
cO2.add(homeData);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM