CS 261 Spring 2005 - PowerPoint PPT Presentation

1 / 13
About This Presentation
Title:

CS 261 Spring 2005

Description:

Vector (and ArrayList, same thing, different API) get around this by ... But will ALWAYS require elements to moved up to make space. Is therefore O(n) worst case ... – PowerPoint PPT presentation

Number of Views:30
Avg rating:3.0/5.0
Slides: 14
Provided by: osue6
Category:
Tags: make | spring

less

Transcript and Presenter's Notes

Title: CS 261 Spring 2005


1
CS 261 Spring 2005
  • Vector Review
  • (Read chapter 6)

2
Arrays, Pro and Con
  • Arrays have nice feature that they are randomly
    accessible - can quickly get to any element
  • Dark side - size must be fixed when created.
  • Often you dont know much much space you need
    until you are done

3
Vector (ArrayList)
  • Vector (and ArrayList, same thing, different API)
    get around this by encapsulating a partially
    filled array.
  • Hide memory management details behind a simple
    API
  • Is still randomly accessible, but now it grows as
    necessary

4
Partially Filled Array
5
Size vs Capacity
  • The size is the logical size - The number of
    elements. What the programmer thinks. Managed by
    an internal data value.
  • The capacity is the size of the physical array.
    Number of elements it can hold.

6
Adding an element
  • Adding an element to end is sometimes easy. Just
    increase the (logical) size, and put new value at
    end.
  • But what happens when the size reaches the
    capacity?
  • Must reallocate new data array - but this detail
    is hidden from user.

7
Reallocation and copy
8
Adding to Middle
  • Adding an element to middle can also force
    reallocation (if the current size is equal to
    capacity)
  • But will ALWAYS require elements to moved up to
    make space
  • Is therefore O(n) worst case

9
Picture of Adding to Middle
  • Must use a loop to make space for new value.
    Careful! Loop from top down

10
Removing an Element
  • Removing an Element will also require sliding
    over to delete the value
  • Therefore is O(n) worst case

11
Picture of Remove Element
  • Remove also requires loop. This time should it be
    from top or bottom?

12
A word on the future
  • Our Vector (and Java lt 1.4) stores values as
    Object - requires a cast when values are moved.
  • Java 5.0 and the future vectors will be generic,
    will not require cast, but declaration is
    different. Watch for this soon.
  • VectorltBankRecordgt foo
  • new VectorltBankRecordgt()

13
Your chance
  • Anti-Quiz time. Give implementation
  • Public class Vector
  • Object get(int index)
  • void put(int index, Object value)
  • void add(Object value)
  • void add(int index, Object value)
  • void remove(int index)
Write a Comment
User Comments (0)
About PowerShow.com