For this method, I have to make a shallow copy of a linked list stack. So,开发者_StackOverflow first I would initialize the linked stack then would I use a for loop to go through the values to copy the stack. But, to put them in the right order, would I just have a nested loop to reverse the group of values? here is what I got so far, am I missing something? This will copy references of all the values in the stack to another stack.
LinkedStack<E> newStack = new LinkedStack<E>();
for(int i = 0; i < objectCount; i++){ //objectCount is figuring out the count
newStack.add[i] = newStack[i];
// do I have to put a for loop here?
return newStack;
}
If the stack in question is this LinkedStack
, then, like most collections, it has a copy-constructor, and one that takes an array. I can't see from your code where is the original stack/array which you want to clone, but this is done easily via:
LinkedStack<E> newStack = new LinkedStack<E>(originalStack);
I suppose that you use a LinkedList for your stack.
According to the Javadoc , the .clone() method, but beware that elements in your stack won't be clone.
精彩评论