Arraylist

Previous Lecture Continued

ArrayList

  • An array of any object type that expands for you as needed
  • Primitive types are NOT allowed.
  • Use angle brackets to indicate the type:
 ArrayList<String> T = new ArrayList<String>();
  • A parameter in the constructor indicates initial capacity:
 ArrayList<Double> D = new ArrayList<Double>(25);

What's so great about ArrayLists?

Pro:

  • You don't have to know size beforehand.
  • Tedium and bugs of resizing an array yourself eliminated. Con:

  • Slower than an array

  • No primitive support! (must use wrappers)
  • Uses more memory

ArrayList<int>     - 4 bytes per element

ArrayList<Integer> - 4 bytes for the value +       --|
                     4 bytes for the data type +     |
                     4 bytes for reference count +   |--- 16 bytes
                     4 bytes for the reference     --|

Newer Syntax

  • "Type inference" allows us to eliminate one of the type specifiers:
 ArrayList<String> T = new ArrayList<String>();
    ArrayList<String> T = new ArrayList<>();

Old Syntax

  • Prior to generics, ArrayList worked on Objects. This was bad because of much casting.

Recreation and Practice

Practice Website

Project Euler No. 15

Starting in the top left corner of a 2x2 grid, there are 6 routes (without backtracking) to the bottom right corner. How many routes are there in a 20x20 grid?

"Dynamic Programming"

Exceptions

Why Exceptions?

  • Errors happen all the time
  • The language should have construct to deal with unusual circumstances

Exceptional Vocabulary

  • Exception
    • an uncommon event or error
  • "Throw an exception" (or raise an exception)
    • to generate the exceptional condition.
  • "Catch an exception"
    • pass control flow to exception handler
  • Exception Handler
    • code that deals with an exception

Java Exception Vocabulary

  • Try block
    • code that can throw an exception placed in this block

Simple Example ###

(see PPT)

Exception Programming tips

  • Exceptions are objects.
  • exceptions must be imported.
  • catch specific exceptions seperately for better bug control.