package day5;
/**
* Write a method to copy one object array to already defined object array.
*
* @author Ritesh
*
*/
public class CopyArray {
// used for checking object
private int intNum;
/**
* constructor to initialize no
*
* @param no
* input value
*/
CopyArray(int no) {
setIntNum(no);
}
/**
* copy array inputed and returns new copy of it
*
* @param cpTemp
* input array
* @return CopyArray[] output array, copy of input array
*/
public static CopyArray[] copyArray(CopyArray[] cpTemp) {
// check if input is null
if (cpTemp == null) {
System.out.println("Invalid Array Input : null value found!!");
return null;
}
// copy content
CopyArray[] cpCopy = new CopyArray[cpTemp.length];
for (int i = 0; i < cpTemp.length; i++)
cpCopy[i] = new CopyArray(cpTemp[i].getIntNum());
return cpCopy;
}
/**
* returns intNum value
*
* @return intNum
*/
public int getIntNum() {
return intNum;
}
/**
* sets intNum value
*
* @param intNum
* sets intNum
*/
public void setIntNum(int intNum) {
this.intNum = intNum;
}
/**
* execution begin from here
*
* @param args
* commandlline arguments
*/
public static void main(String[] args) {
copyArrayDemo();
}
/**
* demonstrates the array copy
*
*/
public static void copyArrayDemo() {
// creating source array
CopyArray[] cpSource = new CopyArray[5];
for (int i = 0; i < class="SpellE">i++)
cpSource[i] = new CopyArray(i);
// copy array
CopyArray[] cpCopy = CopyArray.copyArray(cpSource);
if(cpSource==cpCopy)
System.out.println("Both cpSource and cpCopy arrays references to single object array");
else
System.out.println("Both cpSource and cpCopy arrays references to different object arrays");
// displaying both the arrays
System.out.println("\nDisplaying Source Array : ");
displayArray(cpSource);
System.out.println("\nDisplaying Copied Array : ");
displayArray(cpCopy);
}
/**
* displays the content of inpted array
* @param cpTemp input array
*/
public static void displayArray(CopyArray[] cpTemp) {
if (cpTemp == null) {
System.out.println("Null input found!!");
return;
}
for (int i = 0; i < cpTemp.length; i++)
System.out.println("\t[" + i + "] : " + cpTemp[i].getIntNum());
}
}
No comments:
Post a Comment