队列满,则进行♻️循环处理。

    1. /**
    2. * 先进先出
    3. *
    4. * @author luobo.cs@raycloud.com
    5. * @since 2021/7/25 10:47 上午
    6. */
    7. public class ArrayListQueue<E> {
    8. private final Object[] elements;
    9. private int tail;
    10. private int head;
    11. private int size = 0;
    12. private final int initialCapacity;
    13. public ArrayListQueue(int initialCapacity) {
    14. this.initialCapacity = initialCapacity;
    15. this.elements = new Object[this.initialCapacity];
    16. tail = 0;
    17. head = 0;
    18. }
    19. public int size() {
    20. return size;
    21. }
    22. /**
    23. * 添加
    24. */
    25. public void push(E e) {
    26. if (e == null) {
    27. throw new NullPointerException("element can't be null");
    28. }
    29. if (size >= initialCapacity) {
    30. throw new ArrayIndexOutOfBoundsException("queue is full");
    31. }
    32. elements[tail] = e;
    33. tail++;
    34. size++;
    35. if (tail >= initialCapacity) {
    36. tail = 0;
    37. }
    38. if (size >= initialCapacity) {
    39. size = initialCapacity;
    40. }
    41. }
    42. @SuppressWarnings("unchecked")
    43. public E poll() {
    44. final Object element = elements[head];
    45. if (element == null) {
    46. return null;
    47. }
    48. elements[head] = null;
    49. head++;
    50. size--;
    51. if (head >= initialCapacity) {
    52. head = 0;
    53. }
    54. if (size <= 0) {
    55. size = 0;
    56. }
    57. return (E) element;
    58. }
    59. public static void main(String[] args) {
    60. ArrayListQueue<String> queue = new ArrayListQueue<>(3);
    61. queue.push("11");
    62. queue.push("22");
    63. queue.push("33");
    64. System.out.println(queue.poll());
    65. System.out.println(queue.poll());
    66. System.out.println(queue.poll());
    67. System.out.println(queue.poll());
    68. queue.push("44");
    69. queue.push("55");
    70. queue.push("66");
    71. System.out.println(queue.poll());
    72. System.out.println(queue.poll());
    73. System.out.println(queue.poll());
    74. }
    75. }