Reputation: 51
I'm trying to create a deep copy of a List but I keep getting the error that the new list is empty <[]> even after trying everything to copy the original list.
I'm not sure if my problem lies in the deep copy section of the code or if I made a mistake when adding the elements to the original list. What I have so far is:
public class OwnedPiggyBank
{
List<Coin> bank;
private Owner owner;
public OwnedPiggyBank(Owner owner)
{
this.owner = owner;
bank = new ArrayList<>();
}
public void add(List<Coin> coins)
{
bank.addAll(coins);
}
public List<Coin> deepCopy()
{
List<Coin> coins = new ArrayList<>();
for (Coin c : bank)
{
coins.add(new Coin(c));
}
return coins;
}
... where the test case associated with this is:
public void test()
{
OwnedPiggyBank b = new OwnedPiggyBank("Lola");
List<Coin> coins = new ArrayList<Coin>(Arrays.asList(Coin.PENNY, Coin.LOONIE, Coin.TOONIE));
b.add(coins);
OwnedPiggyBank c = new OwnedPiggyBank(b);
assertEquals(coins, c.deepCopy());
}
Upvotes: 0
Views: 104
Reputation: 632
OwnedPiggyBank doesn't seem to have a constructor that takes in another OwnedPiggyBank as called in 4th statement of the written test case. Adding a constructor like below should fix the issue.
OwnedPiggyBank(OwnedPiggyBank ob){
this.owner = ob.owner;
this.bank = ob.deepCopy();
}
Upvotes: 1
Reputation: 44844
In your constructor public OwnedPiggyBank(Owner owner)
you have
bank = new ArrayList<>();
so of course in deepCopy
bank
is empty
assertEquals(coins, b.deepCopy());
makes more sense
If you wanted to keep the test
case, then you need to do something like
public OwnedPiggyBank(OwnedPiggyBank owner)
{
this.owner = owner;
bank = owner.deepCopy();
}
Upvotes: 2