This section discusses an example to demonstrate the various methods of List interface. We are using two classes ArrayList and LinkedList in the example code. The code below is similar to the previous example, but it performs many List operations. Lets discuss the example code.
Description of program:
This program helps you in storing the large amount of data as a collection. The LinkedList is a part of collection that constructs a list containing the elements of the specified collection. Iterator methods returns the values in the order in which they are stored.
If you want to insert the data in the linkedList then use add() method. The hasNext() method returns true if the iterator contains more elements and the next() method returns the next element in the iteration. To insert and remove the data at first, last and specified position in the linkedList, you use the addFirst(), addLast(), add(), removeFirst(), removeLast() and remove() methods. To retrieve the element with respect to a specified position use the getFirst(), getLast() and get() methods.
Here is the code of program:
import java.util.*;
|
Output of program:
| C:\vinod\collection>javac LinkedListExample.java C:\vinod\collection>java LinkedListExample Linked List Example! Linked list data: 11 22 33 44 Linked list size: 4 Adding data at 1st location: 55 Now the list contain: 55 11 22 33 44 Now the size of list: 5 Adding data at last location: 66 Now the list contain: 55 11 22 33 44 66 Now the size of list: 6 Adding data at 3rd location: 55 Now the list contain: 55 11 99 22 33 44 66 Now the size of list: 7 First data: 55 Last data: 66 Data at 4th position: 22 Data removed from 1st location: 55 Now the list contain: 11 99 22 33 44 66 Now the size of list: 6 Data removed from last location: 66 Now the list contain: 11 99 22 33 44 Now the size of list: 5 Data removed from 2nd location: 99 Now the list contain: 11 22 33 44 Now the size of list: 4 Linked list is empty C:\vinod\collection> |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Linked List Example View All Comments
Post your Comment