Advertisement
jtentor

Queue.java [mejorado]

Oct 3rd, 2021
1,667
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.59 KB | None | 0 0
  1. //
  2. // Created by Julio Tentor <jtentor@fi.unju.edu.ar>
  3. //
  4.  
  5. /*
  6. public interface Queue<E>
  7. extends Collection<E>
  8.  
  9. A collection designed for holding elements prior to processing.
  10. Besides basic Collection operations, queues provide additional insertion,
  11. extraction, and inspection operations. Each of these methods exists in
  12. two forms: one throws an exception if the operation fails, the other
  13. returns a special value (either null or false, depending on the operation).
  14.  
  15. The latter form of the insert operation is designed specifically for use
  16. with capacity-restricted Queue implementations; in most implementations,
  17. insert operations cannot fail.
  18.  
  19. Queues typically, but do not necessarily, order elements in a FIFO
  20. (first-in-first-out) manner. Among the exceptions are priority queues,
  21. which order elements according to a supplied comparator, or the elements'
  22. natural ordering, and LIFO queues (or stacks) which order the elements
  23. LIFO (last-in-first-out). Whatever the ordering used, the head of the
  24. queue is that element which would be removed by a call to remove() or
  25. poll(). In a FIFO queue, all new elements are inserted at the tail of
  26. the queue. Other kinds of queues may use different placement rules.
  27. Every Queue implementation must specify its ordering properties.
  28.  
  29. The offer method inserts an element if possible, otherwise returning
  30. false. This differs from the Collection.add method, which can fail to
  31. add an element only by throwing an unchecked exception. The offer
  32. method is designed for use when failure is a normal, rather than
  33. exceptional occurrence, for example, in fixed-capacity (or "bounded")
  34. queues.
  35.  
  36. The remove() and poll() methods remove and return the head of the queue.
  37. Exactly which element is removed from the queue is a function of the
  38. queue's ordering policy, which differs from implementation to
  39. implementation. The remove() and poll() methods differ only in their
  40. behavior when the queue is empty: the remove() method throws an
  41. exception, while the poll() method returns null.
  42.  
  43. The element() and peek() methods return, but do not remove, the head
  44. of the queue.
  45.  
  46. The Queue interface does not define the blocking queue methods, which
  47. are common in concurrent programming. These methods, which wait for
  48. elements to appear or for space to become available, are defined in
  49. the BlockingQueue interface, which extends this interface.
  50.  
  51. Queue implementations generally do not allow insertion of null elements,
  52. although some implementations, such as LinkedList, do not prohibit
  53. insertion of null. Even in the implementations that permit it, null
  54. should not be inserted into a Queue, as null is also used as a special
  55. return value by the poll method to indicate that the queue contains no
  56. elements.
  57.  
  58. Queue implementations generally do not define element-based versions of
  59. methods equals and hashCode but instead inherit the identity based
  60. versions from class Object, because element-based equality is not
  61. always well-defined for queues with the same elements but different
  62. ordering properties.
  63.  
  64. This interface is a member of the Java Collections Framework.
  65.  
  66.  
  67.  
  68. from https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Queue.html
  69. from https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Queue.html
  70. from https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/Queue.html
  71.  
  72.  */
  73.  
  74.  
  75. import java.lang.reflect.Array;
  76. import java.util.Iterator;
  77.  
  78. public class Queue<ELEMENT> implements Iterable<ELEMENT> {
  79.  
  80.     //region Constants
  81.  
  82.     protected final static Integer defaulDimension = 10;
  83.  
  84.     //endregion
  85.  
  86.     //region Attributes
  87.  
  88.     protected Class<?> elementClass;
  89.     protected ELEMENT [] data;
  90.     protected int head;
  91.     protected int tail;
  92.     protected int count;
  93.  
  94.     //endregion
  95.  
  96.     //region Constructors
  97.  
  98.     public Queue() {
  99.         this(Queue.defaulDimension);
  100.     }
  101.  
  102.     // from https://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java
  103.     @SuppressWarnings("unchecked")
  104.     public Queue(int dimension, ELEMENT... dummy) {
  105.         if (dummy.length > 0) {
  106.             throw new IllegalArgumentException("No se debe facilitar valores para dummy");
  107.         }
  108.         elementClass = dummy.getClass().getComponentType();
  109.         this.data = (ELEMENT []) Array.newInstance(this.elementClass, dimension);
  110.         this.head = 0;
  111.         this.tail = 0;
  112.         this.count = 0;
  113.     }
  114.     //endregion
  115.  
  116.     //region Queue Internal Methods
  117.     protected int next(int pos) {
  118.         if (++pos >= this.data.length) {
  119.             pos = 0;
  120.         }
  121.         return pos;
  122.     }
  123.     //endregion
  124.  
  125.  
  126.     //region Queue Methods
  127.  
  128.     // Operacion EnQueue en la teoría de Estructura de Datos
  129.     //
  130.     // Inserts the specified element into this queue if it is possible to do so
  131.     // immediately without violating capacity restrictions, returning true upon
  132.     // success and throwing an IllegalStateException if no space is currently
  133.     // available.
  134.     public boolean add(ELEMENT element) {
  135.  
  136.         if (this.size() >= this.data.length) {
  137.             throw new IllegalStateException("Cola llena ...");
  138.         }
  139.  
  140.         this.data[this.tail] = element;
  141.         this.tail = this.next(this.tail);
  142.         ++this.count;
  143.  
  144.         return true;
  145.     }
  146.  
  147.     // Operacion peek en la teoría de Estructura de Datos
  148.     //
  149.     // Retrieves, but does not remove, the head of this queue. This method differs
  150.     // from peek only in that it throws an exception if this queue is empty.
  151.     public ELEMENT element() {
  152.  
  153.         if (this.size() <= 0) {
  154.             throw new IllegalStateException("Cola vacía ...");
  155.         }
  156.  
  157.         return this.data[this.head];
  158.     }
  159.  
  160.     // Operacion EnQueue en la teoría de Estructura de Datos
  161.     //
  162.     // Inserts the specified element into this queue if it is possible to do so
  163.     // immediately without violating capacity restrictions. When using a
  164.     // capacity-restricted queue, this method is generally preferable to add(E),
  165.     // which can fail to insert an element only by throwing an exception.
  166.     public boolean offer(ELEMENT element) {
  167.  
  168.         if (this.size() >= this.data.length) {
  169.             return false;
  170.         }
  171.  
  172.         this.data[this.tail] = element;
  173.         this.tail = this.next(this.tail);
  174.         ++this.count;
  175.  
  176.         return true;
  177.     }
  178.  
  179.     // Retrieves, but does not remove, the head of this queue, or returns null if
  180.     // this queue is empty.
  181.     public ELEMENT peek() {
  182.         if (this.size() <= 0) {
  183.             return null;
  184.         }
  185.  
  186.         return this.data[this.head];
  187.     }
  188.  
  189.     // Operacion DeQueue en la teoría de Estructura de Datos
  190.     //
  191.     // Retrieves and removes the head of this queue, or returns null if this queue
  192.     // is empty.
  193.     public ELEMENT pool() {
  194.         if (this.size() <= 0) {
  195.             return null;
  196.         }
  197.  
  198.         ELEMENT result = this.data[this.head];
  199.         this.head = this.next(this.head);
  200.         --this.count;
  201.  
  202.         return result;
  203.     }
  204.  
  205.     // Operacion DeQueue en la teoría de Estructura de Datos
  206.     //
  207.     // Retrieves and removes the head of this queue. This method differs from poll()
  208.     // only in that it throws an exception if this queue is empty.
  209.     public ELEMENT remove() {
  210.         if (this.size() <= 0) {
  211.             throw new IllegalStateException("Cola vacía ...");
  212.         }
  213.  
  214.         ELEMENT result = this.data[this.head];
  215.         this.head = this.next(this.head);
  216.         --this.count;
  217.  
  218.         return result;
  219.     }
  220.     //endregion
  221.  
  222.  
  223.     //region Override Object basic methods
  224.  
  225.     @Override
  226.     public String toString() {
  227.  
  228.         if (this.size() <=0) {
  229.             return "";
  230.         }
  231.  
  232.         // from https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/lang/StringBuilder.html
  233.         StringBuilder sb = new StringBuilder();
  234.         sb.append("[" + this.data[this.head].toString());
  235.  
  236.         for (int cta = 1, pos = this.next(this.head); cta < this.size(); ++cta, pos = this.next(pos)) {
  237.             sb.append(", " + this.data[pos].toString());
  238.         }
  239.  
  240.         sb.append("]");
  241.         return sb.toString();
  242.     }
  243.     //endregion
  244.  
  245.  
  246.     //region Collection Methods
  247.  
  248.     public boolean isEmpty() {
  249.         return this.count <= 0;
  250.     }
  251.  
  252.     public int size() {
  253.         return this.count;
  254.     }
  255.  
  256.     public ELEMENT[] toArray() {
  257.         if (this.size() <= 0) {
  258.             throw new IllegalStateException("Cola vacía ...");
  259.         }
  260.  
  261. //        ELEMENT [] result = (ELEMENT []) new Object[this.size()];
  262.         ELEMENT [] result = (ELEMENT []) Array.newInstance(this.elementClass, this.size());
  263.         for(int i = 0, pos = this.head, cta = this.size(); cta > 0; ++i, pos = this.next(pos), --cta) {
  264.             result[i] = this.data[pos];
  265.         }
  266.         return result;
  267.     }
  268.     //endregion
  269.  
  270.  
  271.     //region Caso Ejemplo b) Methods
  272.  
  273.     public Queue<ELEMENT> union(Queue<ELEMENT> queue2) {
  274.         return union(queue2, 0);
  275.     }
  276.  
  277.     public Queue<ELEMENT> union(Queue<ELEMENT> queue2, int moreElements) {
  278.         Queue<ELEMENT> queue1 = this;
  279.  
  280.         Queue<ELEMENT> result = new Queue<ELEMENT>(queue1.size() + queue2.size() + moreElements);
  281.  
  282.         for(int pos = queue1.head, cta = queue1.size(); cta > 0; pos = queue1.next(pos), --cta) {
  283.             result.offer( queue1.data[pos] );
  284.         }
  285.         for(int pos = queue2.head, cta = queue2.size(); cta > 0; pos = queue2.next(pos), --cta) {
  286.             result.offer( queue2.data[pos] );
  287.         }
  288.  
  289.         return result;
  290.  
  291.     }
  292.     //endregion
  293.  
  294.  
  295.     //region Iterable Methods
  296.  
  297.     @Override
  298.     public Iterator<ELEMENT> iterator() {
  299.         return new QueueIterator(this);
  300.     }
  301.  
  302.     private class QueueIterator implements Iterator<ELEMENT> {
  303.  
  304.         //region Attributes
  305.  
  306.         private Queue<ELEMENT> itQueue;
  307.         private int itCount;
  308.         private int itPos;
  309.  
  310.         //endregion
  311.  
  312.         //region Constructor
  313.  
  314.         public QueueIterator(Queue<ELEMENT> queue) {
  315.             this.itQueue = queue;
  316.             this.itCount = this.itQueue.size();
  317.             this.itPos = this.itQueue.head;
  318.         }
  319.  
  320.         //endregion
  321.  
  322.         @Override
  323.         public boolean hasNext() {
  324.             return this.itCount > 0;
  325.         }
  326.  
  327.         @Override
  328.         public ELEMENT next() {
  329.             if ( !this.hasNext() ) {
  330.                 throw new RuntimeException("Error en el iterador de la cola...");
  331.             }
  332.             ELEMENT item = this.itQueue.data[this.itPos];
  333.             this.itPos = this.itQueue.next(this.itPos);
  334.             --this.itCount;
  335.             return item;
  336.         }
  337.     }
  338.  
  339.     //endregion
  340.  
  341. }
  342.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement