fork(1) download
  1. class CircularBuffer<T> {
  2. private T[] array = (T[]) (new Object[1<<10]);
  3. private int start = 0, end = 0;
  4.  
  5. public T get(int i) {
  6. assert(0 <= i && i < size());
  7. return array[mod(start + i)];
  8. }
  9.  
  10. public void set(int i, T elem) {
  11. assert(0 <= i && i < size());
  12. array[mod(start + i)] = elem;
  13. }
  14.  
  15. public void append(T elem) {
  16. if (size() == array.length) resize();
  17. array[mod(end++)] = elem;
  18. }
  19.  
  20. public void prepend(T elem) {
  21. if (size() == array.length) resize();
  22. array[mod(--start)] = elem;
  23. }
  24.  
  25. public void dropFirst(int count) {
  26. assert(0 <= count && count <= size());
  27. start += count;
  28. }
  29.  
  30. public void dropLast(int count) {
  31. assert(0 <= count && count <= size());
  32. end -= count;
  33. }
  34.  
  35. public int size() {
  36. return mod(mod(end) - mod(start));
  37. }
  38.  
  39. public void clear() {
  40. start = end = 0;
  41. }
  42.  
  43. private int mod(int x) {
  44. return Math.floorMod(x, array.length);
  45. }
  46.  
  47. private void resize() {
  48. T[] array2 = (T[])(new Object[2*array.length]);
  49. for(int i = 0; i < size(); i++) {
  50. array2[i] = get(i);
  51. }
  52. end = size();
  53. start = 0;
  54. array = array2;
  55. }
  56.  
  57. public static void main(String[] args) {
  58. CircularBuffer<Integer> buffer = new CircularBuffer<Integer>();
  59. for (int i = 0; i < 1027; ++i) {
  60. buffer.append(0);
  61. }
  62. System.out.println(buffer.size());
  63. }
  64. }
Success #stdin #stdout 0.04s 711168KB
stdin
1
2
10
42
11
stdout
3