Advertisement
MrDoyle

ArrayList) Practice

Apr 7th, 2021
547
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.05 KB | None | 0 0
  1. import java.util.ArrayList;
  2.  
  3. public class Main {
  4.  
  5.     public static void main(String[] args) {
  6.  
  7.         //initialising the ArrayList object called weeklyTemperatures
  8.         ArrayList<Integer> weeklyTemperatures = new ArrayList<Integer>();
  9.  
  10.         //using the .add method to add elements to the ArrayList
  11.         weeklyTemperatures.add(67);
  12.         weeklyTemperatures.add(89);
  13.         weeklyTemperatures.add(94);
  14.  
  15.         //Printing the elements of the ArrayList
  16.         System.out.println("this is slot 1: " + weeklyTemperatures.get(0));
  17.         System.out.println("this is slot 2: " + weeklyTemperatures.get(1));
  18.         System.out.println("this is slot 3: " + weeklyTemperatures.get(2));
  19.  
  20.         //Adding a new element to the ArrayList
  21.         weeklyTemperatures.add(56);
  22.         System.out.println("this is slot 4: " + weeklyTemperatures.get(3));
  23.  
  24.         //Adding an element to a specific slot location in the ArrayList, this moves the elements after this slot all up one space
  25.         weeklyTemperatures.add(0,68);
  26.         System.out.println("this is slot 1: " + weeklyTemperatures.get(0));
  27.  
  28.         //Printing using a for loop
  29.         System.out.println("Using the for loop");
  30.         for (int i = 0; i < weeklyTemperatures.size();i++){
  31.             System.out.println("This is slot " + (i+1) + ": " + weeklyTemperatures.get(i));
  32.         }
  33.  
  34.         //adding a new element in the 3rd slot
  35.         weeklyTemperatures.add(2,66);
  36.  
  37.         System.out.println("Using the for loop");
  38.         for (int i = 0; i < weeklyTemperatures.size();i++){
  39.             System.out.println("This is slot " + (i+1) + ": " + weeklyTemperatures.get(i));
  40.         }
  41.  
  42.  
  43.  
  44.         //ArrayLists can be of any variable type, integer, double, strings etc
  45.         ArrayList<String> weeklyDays = new ArrayList<String>();
  46.         weeklyDays.add("Monday");
  47.         weeklyDays.add("Tuesday");
  48.         weeklyDays.add("Sunday");
  49.  
  50.         System.out.println(weeklyDays.get(0));
  51.         System.out.println(weeklyDays.get(1));
  52.         System.out.println(weeklyDays.get(2));
  53.  
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement