Created
          June 18, 2015 01:32 
        
      - 
      
- 
        Save ondrej-kvasnovsky/3688ccc9d10f2a023c76 to your computer and use it in GitHub Desktop. 
    Back and forward implementation
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | import java.util.ArrayDeque; | |
| import java.util.Deque; | |
| public class History<ENTITY> { | |
| private Deque<ENTITY> backStack = new ArrayDeque<>(); | |
| private Deque<ENTITY> forwardStack; | |
| private ENTITY current; | |
| private int max; | |
| public History(int max) { | |
| this.max = max; | |
| } | |
| public void record(ENTITY entity) { | |
| if (backStack.size() >= max) { | |
| backStack.pollFirst(); | |
| } | |
| if (!entity.equals(current)) { | |
| current = entity; | |
| backStack.add(entity); | |
| forwardStack = new ArrayDeque<>(); | |
| } | |
| } | |
| public ENTITY back() { | |
| ENTITY back = backStack.pollLast(); | |
| if (back != null) { | |
| forwardStack.add(current); | |
| } | |
| if (current.equals(back)) { | |
| back = backStack.pollLast(); | |
| } | |
| if (back != null) { | |
| current = back; | |
| } | |
| return back; | |
| } | |
| public ENTITY forward() { | |
| ENTITY forward = forwardStack.pollLast(); | |
| if (forward != null) { | |
| backStack.add(current); | |
| } | |
| if (current.equals(forward)) { | |
| forward = forwardStack.pollLast(); | |
| } | |
| if (forward != null) { | |
| current = forward; | |
| } | |
| return forward; | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment