2.1:implement list in java
import java.util.ArrayList;
import java.util.List;
public class ListExample {
public static void main(String[] args) {
// Create a List of Strings using ArrayList
List<String> myList = new ArrayList<>();
// Add elements to the list
myList.add("Apple");
myList.add("Banana");
myList.add("Cherry");
myList.add("Date");
// Access elements by index
System.out.println("Element at index 2: " + myList.get(2)); // Output: Cherry
//only that is enofe
// Modify an element
myList.set(1, "Blueberry");
// Iterate and print elements
System.out.println("List elements:");
for (String fruit : myList) {
System.out.println(fruit);
}
// Check if an element exists in the list
boolean containsApple = myList.contains("Apple");
System.out.println("Contains Apple? " + containsApple); // Output: true
// Get the size of the list
int size = myList.size();
System.out.println("List size: " + size); // Output: 4
// Remove an element
myList.remove("Date");
// Check if the list is empty
boolean isEmpty = myList.isEmpty();
System.out.println("Is the list empty? " + isEmpty); // Output: false
}
}
No comments