I am trying to make a queue by representing it with a one dimensional array. I know people might suggest I will have an easier time by using a list or even the default java queue object but I am here to learn so I do not want to resort to such easy solutions. I have come across a few problems with my implementation so far:
- If the queue is full objects cannot be added.
- Shifting objects.
E.g. QueueArray -> [ ], [A], [B] Shift it so that it ends up like this: QueueArray -> [A], [B], [ ]
Now hear me out, for problem number 1#. My logical thinking tells me to somehow increase the size of the queue array to be able to take in more objects, thing is I'm not sure how to do that without saving all the objects into another temporary array then copying them over to a new array with a bigger size. I'm not even sure if this is a sensible and feasible way to carry this out.
Problem 2# I was thinking of possibly just checking for null objects in the queue array and if they were found, just shift the elements by one index.
Here is my code, I'm also open to other improvements.
import java.util.Scanner;
public class Queue {
Object[] q;
int head, tail;
Scanner in;
public Queue(int size){
q = new Object[size];
menu();
}
public void menu(){
System.out.println("\t");
System.out.println("1. add(x) - Adds the object x to end of the queue");
System.out.println("2. remove() - Removes the first object in the queue");
System.out.println("3. view - Shows contents in queue");
System.out.println("4. exit - Exits program");
System.out.println("Select your operation:"+"\t");
while(true){
in = new Scanner(System.in);
int userInput = in.nextInt();
if(userInput == 1){
System.out.println("Give value of object");
in = new Scanner(System.in);
Object userIn = in.next();
add(userIn);
menu();
}
if(userInput == 2){
remove();
menu();
}
if(userInput == 3){
peek();
menu();
}
if(userInput == 4){
System.exit(0);
}
}
}
// Adds the object to the end of the queue
Object add(Object letter){
// If the queue is not full, add to back of queue
if(tail >= q.length){
System.out.println("Queue is full");
return null;
} else {
q[tail] = letter;
tail++;
}
return tail;
}
// Removes the first object in the queue
Object remove(){
if(q.length == 0){
return null;
} else {
q[head] = null;
head++;
}
return head;
}
// Returns the head, tail and all other objects in the queue
void peek(){
System.out.println("Head: "+q[head]);
System.out.println("Tail: "+q[tail-1]);
System.out.println(q[0]+", "+q[1]+", "+q[2]+", "+q[3]+", "+q[4]+".");
}
public static void main(String[] args){
new Queue(5);
}
}