Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This program uses the StockHolding class that we wrote in the lab for Writing Cl

ID: 3808922 • Letter: T

Question

This program uses the StockHolding class that we wrote in the lab for Writing Classes.


Write a class PortfolioList. A PortfolioList object maintains a portfolio of StockHolding objects by using ArrayList<StockHolding>


PortfolioList only has a no-argument constructor

public class PortfolioDriver {

public static void main(String[] args) {

StockHolding apple = new StockHolding("AAPL", 19, 103.97);

StockHolding ibm = new StockHolding("IBM", 10, 160.8);

StockHolding oracle = new StockHolding("ORCL", 25, 40.76);

StockHolding amazon = new StockHolding("AMZN", 22, 748.27);

PortfolioList pl1 = new PortfolioList();

PortfolioList pl2 = new PortfolioList();

pl1.add(apple);

pl1.add(ibm);

pl2.add(ibm);

pl2.add(oracle);

pl2.add(amazon);

pl2.add(apple);

System.out.println("portfolio 1: " + pl1.toString());

System.out.println("portfolio 2: " + pl2.toString());

System.out.println("Amazon: " + pl2.find("AMZN").toString());

  

pl2.remove("AMZN");

pl2.remove("AAPL");

pl2.remove("IBM");

pl2.remove("ORCL");

System.out.println("portfolio 2: " + pl2.toString());

}

}

Explanation / Answer

HI FRiend, you have not posted StockHolding class. So I can not test.

public class PortfolioList{

  

   private ArrayList<StockHolding> stockList;

  

   public PortfolioList(){

       stockList = new ArrayList<>();

   }

  

   void add(StockHolding stock){ // adds the given StockHolding to the portfolio

       stockList.add(stock);

   }

   void remove(String ticker){ // removes the StockHolding with the given ticker from the portfolio

      

       int index = -1;

      

       for(int i=0; i<stockList.size(); i++)

           if(ticker.equalsIgnoreCase(stockList.get(i).getTicker())){

               index = i;

               break;

           }

       if(index != -1)

           stockList.remove(index);

   }

  

   StockHolding find(String ticker){ // returns a reference to the portfolio element having the given ticker.

       //The method should return null if there is no such element

       int index = -1;

      

       for(int i=0; i<stockList.size(); i++)

           if(ticker.equalsIgnoreCase(stockList.get(i).getTicker())){

               return stockList.get(i);

           }

       return null;

      

   }

   String toString(){ // returns a string containing the toString values of each element

       //separated by newline characters ( )

       String result = "";

       for(StockHolding stock : stockList)

           result = result + stock.toString()+" ";

      

   }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote