import java.util.ArrayList;
public class MyStack<T> {
private ArrayList<T> stack;
// Copy constructor
public MyStack(MyStack<T> s) {
// i know its wrong
for(int i = 0; i < stack.size(); i++) {
this.stack.get(i) = s.stack.get(i);
}
}
}
2 Answers
How about
// Copy constructor
public MyStack(MyStack<T> s) {
this.stack = new ArrayList<T>(s.stack);
}
7 Comments
user2877264
but its private ArrayList<T> stack; i need to copy all the elements
Peter Lawrey
This will copy all the reference to elements in the stack. What is your doubt? What happened when you tried it?
user2877264
i did it this way this.stack = new ArrayList<T>(); for(int i = 0; i < stack.size(); i++) { this.stack.add(s.stack.get(i)); }
user2877264
is it the same thing ?
Peter Lawrey
@user2877264 It is basically the same, just longer. You can look at the Javadoc or code for the constructor to see for yourself.
|
Have you tried to debug at all? An obvious suggestion would be to make sure that you're referencing the correct stack.
2 Comments
Peter Lawrey
Possibly a comment rather than an answer, but I doubt it compiles so you can't debug it.
newtonrd
This should have been a comment. My mistake
get()andset()are opposites.