0

I have a method that updates portfolio of client by his id. But when I use it twice or more, even for other clients, occurs aliasing and all clients get "new" same portfolio.

ArrayList<String> namesOfStocksFromInput=new ArrayList<>();
ArrayList<Integer> amountFromInput=new ArrayList<>();
int clientId;
int selection=0;
Scanner input = new Scanner(System.in);
do
{
try{
selection=input.nextInt();}
switch(selection)   {
    case 1:
            System.out.println("Please enter clients id.");
            try{
                clientId=input.nextInt();}
                catch(Exception e){System.out.println("Wrong input"); break;}
            /* Some tests if client exists, if exists- continue to updating his portfolio*/
            System.out.println("Please enter new stocks for clients portfolio"
                    + " and beside respective amount.");

            /*Method, that separates names and integers from input.
                   namesOfStocks get names, amount list get integers*/
            scanf(namesOfStocksFromInput,amountFromInput);
            /*some tests */
            /*And finally updating the clients portfolio.*/
            updateClientPortfolio(clientId, 
                        new StockPortfolio(namesOfStocksFromInput,amountFromInput));
            break;
    }

}while(selection!=100);

Declaration of updateClientPortfolio:

public void updateClientPortfolio(int id,StockPortfolio portf)  

I tried to use copy constructor- didn't help. So what is the best way to avoid this aliasing?

DenisMag
  • 1
  • 2
  • 1
    a) what is aliasing, b) what does a copy constructor have to do with this problem, c) where exactly does this overwriting happen? in some database? – f1sh Jun 11 '18 at 14:09
  • 2
    "I tried to use copy constructor- didn't help". Then you didn't implement it correctly. Sounds like you need to create a [deep copy](https://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy). Also consider making the class immutable. – Michael Jun 11 '18 at 14:10
  • Looks like you need to clear the namesOfStocksFromInput and amountFromInput lists before calling `scanf`. – yole Jun 11 '18 at 14:34
  • yole, I tried.. And this action clears portfolio of already exist clients ,that were updated... – DenisMag Jun 11 '18 at 14:41
  • Michael, thank you. Correct copy constructor solved the issue. – DenisMag Jun 11 '18 at 15:45

0 Answers0