Implementing an ArrayQueue in java

Problem:

Write a program that implements an ArrayQueue in java.

Output:

Not available.

Solution:

01public class ArrayQueue<E> implements Queue<E> {
02private E[] elements;
03private int front;
04private int back;
05private static final int INITIAL_CAPACITY = 4;
06 
07public ArrayQueue() {
08elements = (E[]) new Object[INITIAL_CAPACITY];
09}
10 
11public ArrayQueue(int capacity) {
12elements = (E[]) new Object[capacity];
13}
14 
15public void add(E element) {
16if (size() == elements.length - 1) {
17resize();
18}
19elements[back] = element;
20if (back < elements.length - 1) {
21++back;
22} else {
23back = 0; //wrap
24}
25}
26 
27public E element() {
28if (size() == 0) {
29throw new java.util.NoSuchElementException();
30}
31return elements[front];
32}
33 
34public boolean isEmpty() {
35return (size() == 0);
36}
37 
38public E remove() {
39if (size() == 0) {
40throw new java.util.NoSuchElementException();
41}
42E element = elements[front];
43elements[front] = null;
44++front;
45if (front == back) { // queue is empty
46front = back = 0;
47}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact