1

I want to create a fixed-size stack and truncate the stack when is full. For this already exists a approach in Creating a fixed-size Stack, but I do not want to implement a class.

It is possible to do something like this?

Stack<String> stack = new Stack<String>(){ private static final long serialVersionUID = 1L; public String push(String item) { if (this.size() == FIXED_SIZE) { //truncate() } return super.push(item); } }; 

And the rest of the stack methods remain the same?

4
  • 2
    Do you want to truncate or clear? Commented Mar 13, 2014 at 0:10
  • I'm sorry, truncate. How can I do this? Commented Mar 13, 2014 at 0:14
  • truncate what?The element doesn't get added Commented Mar 13, 2014 at 0:16
  • 1
    A "fixed size stack" is an array and a counter. Commented Mar 13, 2014 at 0:18

4 Answers 4

2

So this is what I found in the documentation. I did not use or tested it. So I am not sure how this would work out. Because removeElementAt() is inherited from Vector class, and I am hoping that removeElementAt(0), will still remove the element at the bottom.

Stack<String> stack = new Stack<String>(){ private static final long serialVersionUID = 1L; public String push(String item) { if (this.size() == FIXED_SIZE) { this.removeElementAt(0); } return super.push(item); } }; 

And also I am assuming that, what you meant by truncate is to remove the first-in element currently in the list, if you just want to reject the new coming element, you can just return null.

Sign up to request clarification or add additional context in comments.

1 Comment

It is precisely this. Thank you!
0

How about something like this:

 Public class TruncatedStack<T> extends FixedStack<T> { private static final long serialVersionUID = 1L; @Override public String push(String item) { if (this.top == size) { this.top = -1; return super.push(item); } } 

Comments

0

Wrote this off the top of my head (untested). As mentioned in the comments, a fixed size stack is simply an array with a counter to keep track of the top.

public class FixedSizeStack { int top, numElements; int[] baseArray; public FixedSizeStack(int maxSize) { top = 0; numElements = 0; baseArray = new int[maxSize]; } public void push(int num) { baseArray[top] = num; top = (top+1) % baseArray.length; numElements++; } public int pop(int num) { if(numElements == 0) return null; //or throw exception--you've removed too many elements! numElements--; top = (top == 0) ? (baseArray.length - 1) : (top - 1); return baseArray[top]; } } 

Comments

0

Yep, you are almost exactly right. You just need to do a this.remove(0) and then you're done.

Stack<String> stack = new Stack<String>(){ @Override public String push(String item) { if (this.size() == FIXED_SIZE) { this.remove(0) } return super.push(item); } }; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.