Java – Types of Object Copy

/**
 * Reference:
 * <p>
 * http://en.wikipedia.org/wiki/Object_copy
 * <p>
 * http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
 * <p>
 * http://en.wikipedia.org/wiki/Clone_(Java_method)
 * 
 * @author Bhavani P Polimetla
 * @since 11/30/2012
 * 
 */
public class CopyArray {

	private byte[] file;

	public byte[] getFile() {
		return file;
	}

	/**
	 * Good for use within class.
	 * Also called as pass-by-reference
	 * 
	 * @param file
	 */
	public void setFileByReference(byte[] file) {
		this.file = file;
	}

	/**
	 * Good for use within class.
	 * 
	 * @param file
	 */
	public void setFileShallowCopy(byte[] file) {
		if (null == file) {
			this.file = null;
			return;
		}
		this.file = file.clone();
	}

	/**
	 * Always good and must need to use when data was set by other API.
	 * <p>
	 * Disadvantage is,it takes more time, but we need to do it.
	 * 
	 * @param file
	 */
	public void setFileDeepCopy(byte[] file) {
		if (null == file) {
			this.file = null;
			return;
		}
		System.arraycopy(file, 0, this.file, 0, file.length);
	}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s