1 21 22 package org.armedbear.j; 23 24 import java.util.ArrayList ; 25 26 public class Ring 27 { 28 private final int capacity; 29 private final ArrayList list; 30 private int index; 31 private int indexOfNextPop = -1; 32 private String lastPop; 33 34 public Ring(int capacity) 35 { 36 this.capacity = capacity; 37 list = new ArrayList (capacity); 38 } 39 40 public synchronized final int size() 41 { 42 return list.size(); 43 } 44 45 public String get(int i) 46 { 47 if (i >= 0 && i < list.size()) 48 return (String ) list.get(i); 49 else 50 return null; 51 } 52 53 public synchronized void appendToCurrent(String s) 54 { 55 if (list.size() == 0) 56 list.add(s); 57 else { 58 String existing = (String ) list.get(list.size() - 1); 59 list.set(list.size() - 1, existing.concat(s)); 60 } 61 } 62 63 public synchronized void appendNew(String s) 64 { 65 final int size = list.size(); 66 for (int i = size-1; i >= 0; i--) { 68 String existing = (String ) list.get(i); 69 if (existing.equals(s)) { 70 if (i != size-1) { 72 list.remove(i); 73 list.add(s); 74 } 75 return; 76 } 77 } 78 if (size < capacity) 79 list.add(s); 80 else { 81 for (int i = 1; i < size; i++) 82 list.set(i-1, list.get(i)); 83 list.set(capacity-1, s); 84 } 85 } 86 87 public synchronized String peek() 88 { 89 if (list.size() == 0) 90 return null; 91 return (String ) list.get(list.size() - 1); 92 } 93 94 public synchronized String pop() 95 { 96 indexOfNextPop = list.size() - 2; 97 if (list.size() == 0) 98 return null; 99 return lastPop = (String ) list.get(list.size() - 1); 100 } 101 102 public synchronized String popNext() 103 { 104 if (indexOfNextPop < 0) 105 return null; 106 Debug.assertTrue(indexOfNextPop < list.size()); 107 lastPop = (String ) list.get(indexOfNextPop); 108 if (--indexOfNextPop < 0) 109 indexOfNextPop = list.size() - 1; 110 return lastPop; 111 } 112 113 protected synchronized void promoteLast() 114 { 115 if (lastPop != null) 116 promote(lastPop); 117 } 118 119 private void promote(String s) 120 { 121 for (int i = list.size()-1; i >= 0; i--) { 122 String existing = (String ) list.get(i); 123 if (existing.equals(s)) { 124 if (i != list.size()-1) { 125 list.remove(i); 126 list.add(s); 127 } 128 break; 129 } 130 } 131 } 132 } 133 | Popular Tags |