View RSS Feed

Algorithm and Data Structure

Adding and Accessing Queue Elements

Rate this Entry
by , 02-19-2012 at 07:05 AM (2029 Views)
Call add() method for addition of the elements to Queue. This is an inherited type of method of Collection interface.

Different elements are added to a Queue which is explained by this given code.

Java Code: This is the code to explain add operation in Java Queue
Queue myQueue = new LinkedList();
myQueue.add("element 1");
myQueue.add("element 2");
myQueue.add("element 3");
In a Queue, added elements get stored in internal order and they are dependent upon implementation. Same happens with element retrieval.

To get 1st element from queue, use this code:

Java Code: This is the code to get first element of Java Queue
Object firstElement = myQueue.element();
For removing or taking the 1st element, removal method is used. Following code explains it.

Java Code: This is the code to remove elements from Java Queue
Queue myQueue = new LinkedList();
myQueue.add("element 0");
myQueue.add("element 1");
myQueue.add("element 2");

//access via Iterator
Iterator iterator = myQueue.iterator();
while(iterator.hasNext(){
  String element = (String) iterator.next();
}

//access via new for-loop
for(Object object : myQueue) {
    String element = (String) object;
}

Submit "Adding and Accessing Queue Elements" to Facebook Submit "Adding and Accessing Queue Elements" to Digg Submit "Adding and Accessing Queue Elements" to del.icio.us Submit "Adding and Accessing Queue Elements" to StumbleUpon Submit "Adding and Accessing Queue Elements" to Google

Comments