Vocab

  • array
    • collection of similar data types
  • elements
    • each variable in an arrya
  • index and array length
    • index is the value/position assigned to each element
    • array length is how many elements are in the array

Introductions

  • A reference type
  • Array cannot be modified while ArrayLists can change size dynamically

Methods

  • add(int index, element) ...

Traversing ArrayLists

  • For Loop
  • While Loop
  • Enhanced ForLoop

Searching

  • The locating of data within linear structures
  • Searching a structure involves control structures - iterationnal and selection - loop with an if statement
  • For loops are optimal for linear searching because each element needs to be specified sequentiallly with no need to track the index after its executed
  • Order matters sometimes in searching

Sorting

  • Sorting sorts the ArrayList in a specified order (ascending or descending)
  • Collections.sort[(list.name)] - sort in ascending order
  • Collections.sort[(ArrayList,Collections.reverseOrder())] - sort in ascending order

HW

Create an ArrayList that includes 2 of the 4 factors listed below.

  • Sort an ArrayList in descending order and swap the first and last elements
  • Find and display the hashCode of an Arraylist before and after being sorted
  • Return "ascending" if the list is sorted in ascending order, return "descending" if it is descending, and return "neither" if neither
  • Replace 3 elements in an ArrayList with another ArrayList and reverse the order of the new list
import java.util.ArrayList;
import java.util.Collections;

// initialize Array List with strings
ArrayList<String> strlist = new ArrayList<>();

strlist.add("apple");
strlist.add("orange");
strlist.add("3");
strlist.add("yellow");
strlist.add("AX7");
strlist.add("blue98");

System.out.println(strlist);

// reverse order of array list
Collections.reverse(strlist);

// switch first and last
public static void swap(){
    String temp = strlist.get(0);
    int lastindex = strlist.size()-1; 
    strlist.set(0, strlist.get(lastindex));
    strlist.set(lastindex, temp);
    System.out.println("reversed list with first and last element switched: " + strlist);
}
swap()
[apple, orange, 3, yellow, AX7, blue98]
reversed list with first and last element switched: [apple, AX7, yellow, 3, orange, blue98]
import java.util.ArrayList;
import java.util.Collections;

// initialize Array List with strings
ArrayList<String> strlist = new ArrayList<>();

strlist.add("apple");
strlist.add("orange");
strlist.add("3");
strlist.add("yellow");
strlist.add("AX7");
strlist.add("blue98");

// hashCode before sort
System.out.println("Unsorted hashCode: " + strlist.hashCode());

// hashCode after sort
Collections.sort(strlist);
System.out.println("Sorted hashCode: " + strlist.hashCode());
Unsorted hashCode: 903531471
Sorted hashCode: 1218882291