Notes

  • ArrayLists have a reference type
  • The difference bewteeen Arrays and ArrayLists are that ArrayLists have a mutable size while Arrays do not.
  • Can add, find size clear, remove at an index tet an index or checki if the list is empty
  • for loop
  • Enhanced for loop "for each" iterates through each item in the ArrayList to directly get the token of the ArrayList
  • It's a way of organizing anything, particularly Java objects. ArrayLists can only store wrapper classes and java objects which differs from say lists or arrays.
  • Can iterate through and set a variable equal to comparison variable and continue until finished
  • a for loop looking for the index of a certain which can be done with a combination of if/else statements and other conditionals
  • Order matters in a search, for instance if we have 5 ducks, it will iterate sequentially, sorts them in specified order, usually descending or ascending order through sort()

Homework

import java.util.ArrayList;
import java.util.Collections;

// Initializing an ArrayList filled with strings
ArrayList<String> strings = new ArrayList<>();
strings.add("Krish");
strings.add("Don");
strings.add("Nicholas");
strings.add("Nathan");
strings.add("Aadit");

// function to iterate and print out items
public void print(ArrayList<String> strings){
    for (String str : strings){
        System.out.println(str);
    }
}

// 1st bullet (Sort an ArrayList in descending order and swap the first and last elements)
System.out.println("------------------");
Collections.sort(strings, Collections.reverseOrder());
System.out.println("Reverse Order: ");
print(strings);

System.out.println("Swap 1st & Last Element: ");
String temp = strings.get(0);
strings.remove(0);
strings.add(0,strings.get(strings.size()-1));
strings.remove(strings.size()-1);
strings.add(strings.size(), temp);

print(strings);
------------------
Reverse Order: 
Nicholas
Nathan
Krish
Don
Aadit
Swap 1st & Last Element: 
Aadit
Nathan
Krish
Don
Nicholas
// Initializing an ArrayList filled with strings
ArrayList<String> strings = new ArrayList<>();
strings.add("Krish");
strings.add("Don");
strings.add("Nicholas");
strings.add("Nathan");
strings.add("Aadit");

// 2nd bullet point (Find and display the hashCode of an Arraylist before and after being sorted)

// hashCode before being sorted
System.out.println("Unsorted hashCode: " + strings.hashCode());

// sorted hashCode
Collections.sort(strings);
System.out.println("Sorted hashCode: " + strings.hashCode());
Unsorted hashCode: 610100765
Sorted hashCode: -77752291