Monday, October 1, 2018

java - shallow copy of the array but not a copy of the reference





I stumbled upon a problem that I have to create a method which takes no input and return a shallow copy of the array(Not a copy of the reference) of MarketProduct of this Basket.



I know the solution is the following



public class Basket {
private MarketProduct[] marketproducts;

public Basket() {
this.marketproducts = new MarketProduct[0];
}


public MarketProduct[] getProducts() {
return this.marketproducts.clone();


what I don't understand is
1. if it's shallow copy then it's a copy of the reference right? 2. can I use clone method to any object in java? does it copy the reference or the acutal object? if so then the following can be simplified right(instead of using for loop i can use clone?)?



public void add(MarketProduct input) {
MarketProduct[] list = new MarketProduct[marketproducts.length];

for(int i = 0; i < marketproducts.length; i++) {
list[i] = marketproducts[i];
}
list[list.length-1] = input;
this.marketproducts = list;
}

Answer






  1. if it's shallow copy then it's a copy of the reference right?




No. It's a new array containing references to the same objects as the original array





  1. can I use clone method to any object in java?





No. Read the javadoc of Object.clone() and Cloneable to know the rules.




if so then the following can be simplified right(instead of using for loop i can use clone?)?




No, since clone() will give you a new array of the same length, and thus you won't be able to add a new element at the end of the array.


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...