user2877264
user2877264

Reputation: 1

how to implement generic array list copy constructor?

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);
        }
    }
}

Upvotes: 0

Views: 296

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533730

How about

// Copy constructor
public MyStack(MyStack<T> s) {
    this.stack = new ArrayList<T>(s.stack);    
}

Upvotes: 3

newtonrd
newtonrd

Reputation: 2285

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

Upvotes: 0

Related Questions