CS62 - Spring 2021 - Lab 4

Example code in this lecture

   ArrayList

Lecture notes

  • ArrayLists
       - Why do you think its called "ArrayList"?
          - the underlying structure that it stores the data in is an array

  • look at the BasicArraylist class in ArrayList code
       - keep track of two instance variables
          - data (the actual data)
          - size (the number of elements in the data)
             - note this is different than the size of the data array
       
       - Anything new/unusual in the constructor?
          - we cannot create new arrays of type E (or of any type variable)
             - this has to do with how Java implemented generics
          - instead, we create a new array of Objects and type cast it to an E[]

       - look at get and set
          - what do you think the rangeCheck method does?
             - checks to see that the index is within a valid range

       - look at rangeCheck
          - if we want to have a method raise an exception, we use the keyword "throw"
             - remember, exceptions are just classes so we need to create a new instance

  • what are the run times of get, set, and size?
       - Assuming array index operations are O(1), then O(1)

  • adding to an ArrayList
       - so far, we haven't added any functionality over arrays
       
       - what was the main functionality that ArrayLists added over arrays?
          - add/extend

       - how do you think this is done?
          - we allocate some initial array
          - we fill it in as we go
          - what happens when it fills up?
             - we have to create a bigger array!
             - copy over the old values

  • what does the resize method do in the BasicArrayList class in ArrayList code ?
          - creates a new array of type E
          - copies the existing value
          - then sets data to be that new array!

       - look at add method
          - check to see if we're out of space
             - if so, resize
             - we can choose any size that's larger than the existing
             - we'll talk more about how different sizes might affect things

  • look at slides