| 3 | |
| 4 | public class ArrayLists { |
| 5 | public static void main(String[] args) { |
| 6 | ArrayList<String> cars = new ArrayList<String>(); |
| 7 | cars.add("Mercedes"); // adds elements to the ArrayList |
| 8 | cars.add("Audi"); |
| 9 | cars.add("Ferrari"); |
| 10 | cars.add("Jaguar"); |
| 11 | System.out.println(cars.isEmpty()); // prints true if list is empty or false if elements are present |
| 12 | System.out.println(cars.size()); // prints the size / number of elements present in the list |
| 13 | System.out.println(cars); // prints the entire list |
| 14 | System.out.println(cars.get(0)); // prints element at 0th index of ArrayList |
| 15 | cars.set(1, "Bugatti"); // changes value of the element at the specified index |
| 16 | System.out.println(cars); |
| 17 | // loop through the ArrayList |
| 18 | for (int i = 0; i < cars.size(); i++) { |
| 19 | System.out.println(cars.get(i)); |
| 20 | } |
| 21 | Collections.sort(cars); // sort method from collections class is used to sort the elements in the list alphabetically/numerically |
| 22 | System.out.println(cars); |
| 23 | cars.clear(); // clears the list |
| 24 | System.out.println(cars); |
| 25 | } |
| 26 | } |