Hi, I'm a little confused with an assignment. I've try to figure it out for a while but I'm stuck.
The instructions are as follows:
Make 2 classes WrapperShallow and WrapperDeep.
Each class is simply a wrapper class to hold a private array variable. int [] a;
The default constructor for each class should initialize “a”.
Each class should have a toString() and equals().
Each class should have a setArray method that allows you to set the “a” variable.
WrapperShallow should have an invalid copy constructor.
public WrapperShallow(WrapperShallow ws){
a = ws.a;
}
WrapperDeep should have a properly functioning copy constructor.
public WrapperDeep(WrapperDeep ws){
a = new int[3];
for(int i = 0; i < 3; i++)
a[i]=ws.a[i];
}
Think about why shallow is wrong and deep is correct! What happens to the old “a” in the WrapperDeep copy constructor? (think garbage collection)
Example Output:
--------------------Configuration: <Default>--------------------
**** TESTING SHALLOW OBJECTS ****
inital shallow object contains
7 17 77
copy shallow object contains
7 17 77
inital shallow object changed to
13 14 15
copy shallow object not changed contains
13 14 15
WOOPS! ws.equals(ws2) is true
**** TESTING DEEP OBJECTS ****
inital deep object contains
2 3 4
copy deep object contains
2 3 4
inital deep object changed to
7 6 -5
copy deep object not changed contains
2 3 4
RIGHT! wd.equals(wd2) is false
Process completed.
So far I have this:
class WrapperShallow { private int[] a = new int[2]; public void setArray() { a[0] = 7; a[1] = 17; a[2] = 77; for(int i = 0; i < 3; i++) { System.out.println("Inital shallow object contain the numbers:\n"); System.out.print(a[i] + " "); } } public WrapperShallow (WrapperShallow ws) { a = ws.a; } public String toString() { return Integer.toString(a[0]); } public boolean equal(WrapperShallow ws2) { return a.equals(ws2); } } class WrapperDeep { private int[] a = new int[2]; public void setArray() { a[0] = 7; a[1] = 17; a[2] = 77; for(int i = 0; i < 3; i++) { System.out.println("Inital shallow object contain the numbers:\n"); System.out.print(a[i] + " "); } } public WrapperDeep(WrapperDeep wd) { a = new int[3]; for (int i = 0; i < 3; i++) a[i] = wd.a[i]; } public String toString() { return Integer.toString(a[0]); } public boolean equal(WrapperDeep wd2) { return a.equals(wd2); } } public class WrapperDemo { public static void main(String[] args) { WrapperShallow ws = new WrapperShallow(); ws.setArray(); } }
Just ignore the toString and Equals. I'll change those later.
The error I'm trying to understand is in this line "WrapperShallow ws = new WrapperShallow();"
I think I'm supposed to pass an array in the parentheses however I get an error every time I try to. I know I'm supposed to send something because it is supposed to receive something. Am I approaching this problem in the correct way? Any help would be greatly appreciated.
Thank you!