I have a Portfolio class that also has linkedlist of Investment class (example - Google is an instance of Investment), each investment has a trade history (another linked list) with data for each trade.
When the user want to make a trade (buy google stocks for 5K) I need to find if the investment (in google) already exists in the investmentsList. If it doesn't - add new investment (and add the trade for its trade history), If it does - just add another link to google's tradeHistory linkedlist.
The problem - I need findInvestment method to return a reference to google (investment instance) from the investmentList so I can update its trade history.The method returns a listIterator rather than a reference to a location in investmentList(should be Investment Class). How should I correct findInvestment? (found=iter is wrong)
public class Portfolio {
private LinkedList<Investment> investmentsList;
public Portfolio() {
investmentsList = new LinkedList<Investment>();
}
public void addInvestment(String symbol, double money){
Investment invest = findInvestment(symbol);
if (invest == null) {
System.out.println("symbol does not exist");
getInvestmentsList().add(new Investment(symbol,money));
System.out.println("New invetment has been added to your portfolio - " +symbol);
} else {
invest.addTrade(symbol,money);
System.out.println("A new trade has been added to the current investment - " + symbol);
}
}
public Investment findInvestment(String symbol){
Investment found = null;
ListIterator<Investment> iter = investmentsList.listIterator();
while (iter.hasNext()) {
if (iter.next().getSymbol().equals(symbol)) {
found = iter;
return found;
System.out.println("Found the symbol");
}
}
return found;
}
Simply hold an Investment
- or in java 8 Optional<Investment>
Instead of the linked list:
private Map<String, Investment> investmentsBySymbol;
public Investment findInvestment(String symbol){
Investment found = investmentsList.get(symbol);
return found;
}
Also BigDecimal is a better choice than double as
new BigDecimal("3.10");
has a precision of 2, and doubles are always inprecise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With