CH4-Arrays and ArrayLists

Chapter 4: Arrays and ArrayLists

Overview

  • Introduction to Arrays and ArrayLists in Java

Arrays

  • Definition: A fixed-length data structure containing related data items of the same type.

  • Indexing: Elements accessed via an index.

  • Type: In Java, arrays are objects (reference types).

  • Properties:

    • Length is known and stored in a length instance variable.

    • Elements can be either primitive or reference types.

Arrays of Objects

  • Definition: Elements can be instances of any Java class.

  • Example:

    • Declaration: Student[] topStudents = new Student[5];

    • Type of the array corresponds to the objects it holds.

Coding: Arrays of Objects

Steps to code with PassFailActivity objects:

  1. Declare an array based on user input.

  2. Create objects and populate the array.

  3. Modify an element (e.g., change 2nd element's score).

  4. Print all elements of the array.

Example Code Fragment:

int Nb; 
Scanner keyboard = new Scanner(System.in);  
System.out.print("Please provide array elements number: ");  
Nb = keyboard.nextInt();  
PassFailActivity[] Arr = new PassFailActivity[Nb];  

ArrayList

  • Definition: A dynamic array that can grow and shrink.

  • Comparison to Arrays: Unlike arrays, the size of an ArrayList can change and it can store multiple object types.

Collections and Class ArrayList

  • Java Collections: ArrayList is a basic collection class in java.util package.

  • Import statement: import java.util.ArrayList;

Syntax for ArrayList

  • Declaration: ArrayList<E> List = new ArrayList<E>();

  • Type Placeholder: E denotes the type of elements the ArrayList can hold (must be a reference type).

Useful ArrayList Methods

  • add(E e): Adds an element to the end.

  • clear(): Removes all elements.

  • contains(Object o): Checks if an element is present.

  • get(int index): Returns the element at specified position.

  • remove(int index): Removes an element at specified position.

  • Note on size: size() returns the number of elements.

Coding: ArrayList

Steps for arraylist of GradedActivity objects:

  1. Create an ArrayList.

  2. Add elements and print size.

  3. Access specific elements.

  4. Modify elements and verify changes.

  5. Clear the ArrayList.

Example Code Fragment:

ArrayList<GradedActivity> MyList = new ArrayList<GradedActivity>();  
MyList.add(new GradedActivity("Name1"));  

Additional Methods for ArrayList

  • removeAll(Collection<?> c): Remove all elements contained in specified collection.

  • trimToSize(): Adjusts capacity to match size.