3
\$\begingroup\$

First time I'm using stackexchange. I'm in 8th standard. I tried to implement Queue in Java. I wrote something like this> Right now I'm not able to test it because I don't have JVM in my machine. So I just wanted to know Is this correct implementation? Am I going in the right direction?

 import java.lang.*;
 import java.util.*;

 public class Queue
{
public static void main(string[] args)
{
    LinkedList l1=new LinkedList();
    InputstreamReaderir=new InputstreamReader(System.in);
    BufferReader bf=new BufferReader(ir);
    System.out.println("Enter the number of elements to be inserted into queue");
    string str;
    str=bf.readline();
    System.out.println("Enter your Choice: ");
    System.out.println("1->Insert 2->Delete 3->Display 3->Exit");
    string choice;
    choice.readline();
    for(;;)
    {
        switch
        {
            case 1:l1.insertrear();
                   break;
            case 2:l1.deletefront();
                break;
            case 3: system.out("Contents of Queue are:" +l1);
                break;
            default: exit;
        }
    }
}
\$\endgroup\$
  • 2
    \$\begingroup\$ you might find ideone.com helpful if you don't have a proper dev environment setup. \$\endgroup\$ – greatwolf Dec 21 '11 at 11:01
  • 1
    \$\begingroup\$ I don't really see a "queue" implementation here. You initialize a regular LinkedList and then attempt to call methods on it that don't exist. \$\endgroup\$ – RoToRa Dec 21 '11 at 15:45
5
\$\begingroup\$

you're on the right track with using a LinkedList, this is one of the easiest ways to implement your own Queue - I hope this is an exercise, since you should otherwise use Java's built-in Queue.

I must confess I found your question interesting and decided to write a Queue so as to demonstrate. Note that you should create a class for your custom Queue. If you implement the whole thing in main, there'll be no way to reuse the code.

So you'd create a new file, let's call it Queue.java. It would look something like this:

import java.util.*;

public class Queue<T> implements Iterable<T> {

    private LinkedList<T> elements = new LinkedList<T>();

    public void enqueue(T element) {
        elements.add(element);
    }

    public T dequeue() {
        return elements.removeFirst();
    }

    public T peek() {
        return elements.getFirst();
    }

    public void clear() {
        elements.clear();
    }

    public int size() {
        return elements.size();
    }

    public boolean isEmpty() {
        return elements.isEmpty();
    }

    @Override
    public Iterator<T> iterator() {
        return elements.iterator();
    }
}

Notice that that the code is extremely simple - no method's implementation is longer than one line. However, I don't know your level of experience so there might be two weird things in here: the use of Generics and the implements Iterable<T>.

Generics

The <T> means you can put any Java object into the Queuekeeping Type safety. This means, when you call Queue.Dequeue(), the result will still have the same type that it had when you Enqueued it.

Iterable<T>

Oracle says:

Implementing this interface allows an object to be the target of the foreach statement.

Note that you don't need to know more, because we simply delegate this responsibility to LinkedList.iterator() which does the work for us.

Below is some code to test your new Queue. Play around with it. You can add other queue tests to main, for instance:

testQueue(true, false, true, true);

or

testQueue(0.5, 3.6, -5.4, 0.0);

to test putting different types of data into your Queue.
If anything remains unclear, feel free to leave a comment, and I'll update my answer.

public class Main {

    public static void main(String[] args) {
        testQueue(1, 2, 3, 4, 5);
        testQueue("first", "second", "third");
    }

    private static <T> void testQueue(T... elements) {
        outputLine("testing a Queue<%s>", getClassOf(elements));
        Queue<T> queue = new Queue<T>();
        outputSize(queue);
        enqueueElementsInto(queue, elements);
        outputSize(queue);
        loopOverAllElementsOf(queue);
        dequeueAllFrom(queue);
        outputSize(queue);
        outputLine("---");
    }

    private static <T> void outputSize(Queue<T> queue) {
        outputLine("empty: %s, size: %s elements", queue.isEmpty(), queue.size());
    }

    private static <T> void enqueueElementsInto(Queue<T> queue, T... elements) {
        outputLine("enqueueing: ");
        for (T element : elements) {
            queue.enqueue(element);
            output(element + " ");
        }
    }

    private static <T> void loopOverAllElementsOf(Queue<T> queue) {
        outputLine("Queue contains: ");
        for (T element : queue) {
            output(element + " ");
        }
    }

    private static <T> void dequeueAllFrom(Queue<T> queue) {
        outputLine("dequeueing: ");
        while (!queue.isEmpty()) {
            T next = queue.peek();
            T dequeued = queue.dequeue();
            outputLine("expected: %s ", next);
            output("dequeued: %s ", dequeued);
        }
    }

    private static void outputLine(String format, Object... params) {
        output('\n' + format, params);
    }

    private static void output(String format, Object... params) {
        System.out.print(String.format(format, params));
    }

    private static <T> String getClassOf(T... elements) {
        String nameOfArray = elements.getClass().getSimpleName();
        return nameOfArray.substring(0, nameOfArray.length() - 2);
    }
}

output:

testing a Queue<Integer>
empty: true, size: 0 elements
enqueueing: 1 2 3 4 5 
empty: false, size: 5 elements
Queue contains: 1 2 3 4 5 
dequeueing: 
expected: 1 dequeued: 1 
expected: 2 dequeued: 2 
expected: 3 dequeued: 3 
expected: 4 dequeued: 4 
expected: 5 dequeued: 5 
empty: true, size: 0 elements
---
testing a Queue<String>
empty: true, size: 0 elements
enqueueing: first second third 
empty: false, size: 3 elements
Queue contains: first second third 
dequeueing: 
expected: first dequeued: first 
expected: second dequeued: second 
expected: third dequeued: third 
empty: true, size: 0 elements
---
\$\endgroup\$
  • \$\begingroup\$ Very nice, but I would have liked to let student do a bit more of his homework. \$\endgroup\$ – Chris Marasti-Georg Dec 28 '11 at 17:48
  • \$\begingroup\$ @Chris thank you. Well, I just couldn't resist, I hadn't created a generic type in Java yet nor had I tried a simple Queue... curiosity got the better of me. Anyway, he'll have a hard time explaining this to his teacher if he doesn't understand it ;-) \$\endgroup\$ – Adam Dec 28 '11 at 17:55
1
\$\begingroup\$

It needs some improvement but you're definitely in the right direction. There are some typos (string should be String, for example) but I'm sure that you will be able to fix them.

Just two notes:

1, Here maybe you want to read some initial elements:

System.out.println("Enter the number of elements to be inserted into queue");
string str;
str=bf.readline();

2, The menu printing, input reading logic currently runs only once.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.