This program uses the StockHolding class that we wrote in th
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. A PortfolioList
keeps an ArrayList<StockHolding>
has a no-argument constructor
Solution
PortfolioList.java
import java.util.ArrayList;
public class PortfolioList {
ArrayList<StockHolding> list = new ArrayList<StockHolding>();
public PortfolioList(){
}
public void add(StockHolding stock){
list.add(stock);
}
public void remove(String ticker){
for(StockHolding s: list){
if(s.getTicker().equals(ticker)){
list.remove(s);
}
break;
}
}
public StockHolding find(String ticker) {
for(StockHolding s: list){
if(s.getTicker().equals(ticker)){
return s;
}
}
return null;
}
public String toString() {
String str = \"\";
for(StockHolding s: list){
str = str + s.toString()+\"\ \";
}
return str;
}
}
PortfolioDriver.java
public class PortfolioDriver {
public static void main(String[] args) {
PortfolioList p1 = new PortfolioList();
PortfolioList p2 = new PortfolioList();
p1.add(new StockHolding(\"AAPL\",3, 100 ));
p1.add(new StockHolding(\"AAPP\",2, 200 ));
p2.add(new StockHolding(\"ABCD\",3, 500 ));
p2.add(new StockHolding(\"EFGH\",6, 600 ));
p2.add(new StockHolding(\"IJKL\",7, 700 ));
p2.add(new StockHolding(\"MNOP\",8, 800 ));
System.out.println(p1.toString());
System.out.println(\"--------------------------------\");
System.out.println(p2.toString());
StockHolding s = p1.find(\"AAPP\");
System.out.println(s.toString());
StockHolding s1 = p2.find(\"IJKL\");
System.out.println(s1.toString());
System.out.println(\"-------Removed second portfolio all objects---------------\");
p2.remove(\"ABCD\");
p2.remove(\"EFGH\");
p2.remove(\"IJKL\");
p2.remove(\"MNOP\");
System.out.println(p2.toString());
}
}
Output:
Stock AAPL, 3, shares bought at 100.0, current price 0.0
Stock AAPP, 2, shares bought at 200.0, current price 0.0
--------------------------------
Stock ABCD, 3, shares bought at 500.0, current price 0.0
Stock EFGH, 6, shares bought at 600.0, current price 0.0
Stock IJKL, 7, shares bought at 700.0, current price 0.0
Stock MNOP, 8, shares bought at 800.0, current price 0.0
Stock AAPP, 2, shares bought at 200.0, current price 0.0
Stock IJKL, 7, shares bought at 700.0, current price 0.0
-------Removed second portfolio all objects---------------

