0
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);
        }
    }
}
3
  • get() and set() are opposites. Commented Oct 14, 2013 at 0:13
  • the class is generic MyStack<T> as well as ArrayList<T> idk y its not showing it Commented Oct 14, 2013 at 0:24
  • Just for future reference @user2877264 - this code won't successfully compile, because a retrieval can't be used as an assignment target, only a variable can. Commented Oct 14, 2013 at 0:53

2 Answers 2

3

How about

// Copy constructor
public MyStack(MyStack<T> s) {
    this.stack = new ArrayList<T>(s.stack);    
}
Sign up to request clarification or add additional context in comments.

7 Comments

but its private ArrayList<T> stack; i need to copy all the elements
This will copy all the reference to elements in the stack. What is your doubt? What happened when you tried it?
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)); }
is it the same thing ?
@user2877264 It is basically the same, just longer. You can look at the Javadoc or code for the constructor to see for yourself.
|
0

Have you tried to debug at all? An obvious suggestion would be to make sure that you're referencing the correct stack.

2 Comments

Possibly a comment rather than an answer, but I doubt it compiles so you can't debug it.
This should have been a comment. My mistake

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.