In: Computer Science
Problem 4 •
Use Java Collections to write a small program using NetBeans to do the following:
1. Create a queue object of Integer items, myQueue.
2. Create a stack object of Integer items, myStack.
3. Enqueue the integers 10, 20. 30, .., 100 into myQueue, in that order.
4. Push the integers 10, 20, 30, ..., 100 into myStack, in that order.
5. Display the message: "Here are the elements of myQueue:".
6. Remove and display the front element of the queue until myQueue becomes empty.
7. Display the message: "And here are the elements of myStack:".
8. Remove and display the top element of the stack until myStack becomes empty.
CODE:
import java.util.*;
public class Main {
public static void main(String[] args) {
Queue<Integer> myQueue = new
LinkedList<Integer>();
Stack<Integer> myStack= new
Stack<Integer>();
for (int i = 10; i <=100 ; i+=10)
{ myQueue.add(i);
myStack.push(i);
}
System.out.println("Here are the elements of myQueue:"+
myQueue);
while (!myQueue.isEmpty()){
int remele = myQueue.remove();
System.out.println("removed element from the front:"+ remele);
if(!myQueue.isEmpty())
{
System.out.println(myQueue);
int front = myQueue.peek();
System.out.println("front element of myQueue:" + front);
System.out.println("-----------------------------------------");
}
}
System.out.println("================================================");
System.out.println("And here are the elements of myStack: " +
myStack);
while (!myStack.isEmpty()){
int poppedele = myStack.pop();
System.out.println("removed element from the top:"+
poppedele);
if(!myStack.isEmpty())
{
System.out.println(myStack);
int top = myStack.peek();
System.out.println("top element of myQueue:" + top);
System.out.println("-----------------------------------------");
}
}
}
}
OUTPUT: