I have use java stack data structure to maintain data. I have limit my stack to be size 50. What I want to do get latest 5 data from the stack from one call. I thought method sublist(0,5) would do it. But unfortunately method returns last 5 data since that method inherited from java.util.list is there any way to do this. Or is there any other data structure which fulfill my requirment. pls help me. Thanks in advance.
P.s I want to remain lates 5 data in the stack after i retrive.
Stack stack = new Stack();
for(int i=0; i<10;i++){
stack.push(""+i);
}
for(int k= 0 ;k<11;k++){
System.out.println(stack.subList(0,5));
}
out put of this will be {0,1,2,3,4}. But I want to get {9,8,7,6,5}
If
sublist(0,5)returns the wrong end of your stack, try changing your indices. Instead of starting from 0, start fromstack.size()-6.As others pointed out you can
pop()5 times as well. In functional languages the operation you are looking for simply referred to astake 5. It is easy to implement it yourself, but you’d have to derive your own stack class in Java.Another important point: When you
pop()5 times, those elements will be removed from the stack. This may or may not be what you intend. However, keep in mind, thatsublistwill return you a list that may modify the stack itself, so you can easily run into integrity problems there.Hence, I suggest you write your own stack class and implement a
take(n)method that performs asublistcall and copies the results into a fresh list, such that the ultimately returned list cannot affect your original stack.