Java Collection Examples: ArrayList, LinkedList, Vector, Stack
1. ArrayList Version
import java.util.*;
class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("A1");
list.add("A2");
list.add("A3");
list.add("A4");
list.add("A5");
list.add("A6");
list.add("A7");
list.add(0, "A0");
list.set(2, "Hello");
list.remove(5);
list.remove(5);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}
2. LinkedList Version
import java.util.*;
class LinkedListExample {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("A1");
list.add("A2");
list.add("A3");
list.add("A4");
list.add("A5");
list.add("A6");
list.add("A7");
list.add(0, "A0");
list.set(2, "Hello");
list.remove(5);
list.remove(5);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
Java Collection Examples: ArrayList, LinkedList, Vector, Stack
}
}
}
3. Vector Version
import java.util.*;
class VectorExample {
public static void main(String[] args) {
Vector<String> list = new Vector<>();
list.add("A1");
list.add("A2");
list.add("A3");
list.add("A4");
list.add("A5");
list.add("A6");
list.add("A7");
list.add(0, "A0");
list.set(2, "Hello");
list.remove(5);
list.remove(5);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}
4. Stack Version (Used Like a List)
import java.util.*;
class StackExample {
public static void main(String[] args) {
Stack<String> list = new Stack<>();
list.add("A1");
list.add("A2");
list.add("A3");
list.add("A4");
list.add("A5");
list.add("A6");
list.add("A7");
list.add(0, "A0");
list.set(2, "Hello");
list.remove(5);
Java Collection Examples: ArrayList, LinkedList, Vector, Stack
list.remove(5);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}
5. Stack Version (Proper LIFO using push/pop)
import java.util.*;
class StackProperExample {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
// Push elements (LIFO order)
stack.push("A1");
stack.push("A2");
stack.push("A3");
stack.push("A4");
stack.push("A5");
stack.push("A6");
stack.push("A7");
// Insert "A0" at bottom (simulated)
Stack<String> temp = new Stack<>();
while (!stack.isEmpty()) {
temp.push(stack.pop());
}
stack.push("A0");
while (!temp.isEmpty()) {
stack.push(temp.pop());
}
// Replace at index 2
stack.set(2, "Hello");
// Pop top two elements
stack.pop();
stack.pop();
// Print stack (bottom to top)
for (int i = 0; i < stack.size(); i++) {
System.out.println(stack.get(i));
}
}
}