- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to get elements of a LinkedList in Java
Problem Description
How to get elements of a LinkedList?
Solution
Following example demonstrates how to get elements of LinkedList using top() & pop() methods.
import java.util.*;
public class Main {
private LinkedList list = new LinkedList();
public void push(Object v) {
list.addFirst(v);
}
public Object top() {
return list.getFirst();
}
public Object pop() {
return list.removeFirst();
}
public static void main(String[] args) {
Main stack = new Main();
for (int i = 30; i < 40; i++)stack.push(new Integer(i));
System.out.println(stack.top());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}
Result
The above code sample will produce the following result.
39 39 38 37
The following is an another example to get elements of LinkedList using top() & pop() methods.
import java.util.LinkedList;
public class Demo {
public static void main(String[] args) {
LinkedList lList = new LinkedList();
lList.add("1");
lList.add("2");
lList.add("3");
lList.add("4");
lList.add("5");
System.out.println("LinkedList is : ");
for(int i = 0; i< lList.size(); i++) {
System.out.println(lList.get(i));
}
}
}
The above code sample will produce the following result.
LinkedList is : 1 2 3 4 5
java_data_structure.htm
Advertisements