GamerBhai02

10. Array/Linked List

Jan 16th, 2025
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.94 KB | Source Code | 0 0
  1. import java.util.*;
  2. public class ListDemo {
  3.     public static void main(String[] args) {
  4.         System.out.println("ArrayList Demonstration: ");
  5.         ArrayList<String> al = new ArrayList<>();
  6.         al.add("Apple");
  7.         al.add("Banana");
  8.         al.add("Cherry");
  9.         System.out.println(al);
  10.         al.size();
  11.         System.out.println("Using for loop");
  12.         for(String s: al) {
  13.             System.out.print(s+" ");
  14.         }
  15.         System.out.println("\n"+"Using index");
  16.         System.out.println(al.get(0));
  17.         System.out.println("Using for-each loop");
  18.         for(int i=0;i<al.size();i++) {
  19.             System.out.print(al.get(i)+" ");
  20.         }
  21.         al.remove(0); //Remove using index
  22.         System.out.println("\n"+al);
  23.         al.remove("Cherry"); //Remove using the value
  24.         System.out.println(al);
  25.         al.add("Cherry"); //adding again
  26.         System.out.println(al);
  27.         System.out.println(al.indexOf("Cherry")); //Returns the first occurring index of element
  28.         al.clear(); //Removes all the elements
  29.         System.out.println(al);
  30.     }
  31. }
Add Comment
Please, Sign In to add comment