how to use the offer() method in the LinkedList using collections in java
Previous | Home | Next |
In this example we will see how can we use the offer() method on LinkedList.
In this example we have created a class CollectionExample. For using LinkedList we have
to import the java.util package.
In this example we have used the offer() method on the LinkedList object which add an element to the end of the list. This method has the following syntax:
offer(Object obj);
This offer adds the specified element as the last(tail) element of the list.
In the following example we have created a Linked list and added some element to it. Then we have used the offer method on its object which add the specified element to the end of the list. The following statement in this example does this work:list.offer("offer");
package r4r.co.in;
import java.util.*;
import java.util.ListIterator;
public class CollectionExample {
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
LinkedList<Object> list=new LinkedList<Object>(); // creating a LinkedList of Object type elements
list.add(1); // adding integer values to the LinkedList
list.add(2);
list.add("r4r"); // adding String values to the LinkedList
list.add("shashi");
list.add("s/w engineer");
list.offer("offer"); //By default this offer method will add the element at the end of the list
list.offerFirst("offerfirst"); // this offerFirst method will add the element at the start of the list
list.offerLast("offerlast"); // This method will add the element at the end of the list
ListIterator<Object> ltr=list.listIterator(); // Invoking the ListIterator on the list for iterating through the list
while(ltr.hasNext())
{
System.out.println(ltr.next()); // displaying the contents of the list
}
}
}
The output of the above program will be the following,
offerfirst
1
2
r4r
shashi
s/w engineer
offer
offerlast
Previous | Home | Next |