Category : Java | Sub Category : Java.util Package | By Prasad Bonam Last updated: 2023-07-12 16:29:16 Viewed : 73
Example of using ArrayList, LinkedList, and Vector in Java:
Here is an example of using ArrayList, LinkedList, and Vector in Java:
ArrayList Example:
javaimport java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
// Create an ArrayList of integers
ArrayList<Integer> numbers = new ArrayList<>();
// Add elements to the ArrayList
numbers.add(10);
numbers.add(20);
numbers.add(30);
// Access elements by index
System.out.println("Element at index 0: " + numbers.get(0));
// Update elements
numbers.set(1, 25);
System.out.println("Updated element at index 1: " + numbers.get(1));
// Remove elements
numbers.remove(2);
System.out.println("Size after removing an element: " + numbers.size());
// Iterate over the ArrayList
System.out.println("Elements in the ArrayList:");
for (int number : numbers) {
System.out.println(number);
}
}
}
LinkedList Example:
javaimport java.util.LinkedList;
public class LinkedListExample {
public static void main(String[] args) {
// Create a LinkedList of strings
LinkedList<String> names = new LinkedList<>();
// Add elements to the LinkedList
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// Access elements by index
System.out.println("Element at index 0: " + names.get(0));
// Update elements
names.set(1, "Brian");
System.out.println("Updated element at index 1: " + names.get(1));
// Remove elements
names.remove(2);
System.out.println("Size after removing an element: " + names.size());
// Iterate over the LinkedList
System.out.println("Elements in the LinkedList:");
for (String name : names) {
System.out.println(name);
}
}
}
Vector Example:
javaimport java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
// Create a Vector of doubles
Vector<Double> prices = new Vector<>();
// Add elements to the Vector
prices.add(9.99);
prices.add(19.99);
prices.add(29.99);
// Access elements by index
System.out.println("Element at index 0: " + prices.get(0));
// Update elements
prices.set(1, 24.99);
System.out.println("Updated element at index 1: " + prices.get(1));
// Remove elements
prices.remove(2);
System.out.println("Size after removing an element: " + prices.size());
// Iterate over the Vector
System.out.println("Elements in the Vector:");
for (double price : prices) {
System.out.println(price);
}
}
}
In these examples, we create instances of ArrayList, LinkedList, and Vector, and perform operations such as adding elements, accessing elements by index, updating elements, removing elements, and iterating over the collections. Each implementation has its own methods and characteristics, but the basic usage and functionality are similar across all three.