0% found this document useful (0 votes)
2 views

lecture18 (1)

The document introduces ArrayLists in Java, highlighting their advantages over traditional arrays, particularly their dynamic sizing and flexibility in element management. It explains how ArrayLists can automatically resize, maintain order, and provide various methods for adding, retrieving, and removing elements. Additionally, it discusses the importance of using type parameters (generics) for ArrayLists and provides examples of common operations and potential pitfalls when modifying the list.

Uploaded by

skshrcxgs2
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

lecture18 (1)

The document introduces ArrayLists in Java, highlighting their advantages over traditional arrays, particularly their dynamic sizing and flexibility in element management. It explains how ArrayLists can automatically resize, maintain order, and provide various methods for adding, retrieving, and removing elements. Additionally, it discusses the importance of using type parameters (generics) for ArrayLists and provides examples of common operations and potential pitfalls when modifying the list.

Uploaded by

skshrcxgs2
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Unit 7: ArrayList

Introduction to ArrayLists
Problem with Arrays
Consider the following problem: Read words from a text
file and
store the data in memory.
String[] allWords = new String[2500];

Problem: You don't know how many words the text file
contains.

The array above may be enough to store all the words


from Wordle(about 2300).

But what if the text file contains all of the works of


Shakespeare?
– Hard to create an array of the appropriate size. 2
String[] allWords = new String[2500];

creates an array that can store up to 2500 words. While


this may work for smaller datasets, like Wordle’s word
list (about 2300 words), it becomes problematic for
larger datasets, like all of Shakespeare’s works. If the
text file contains more than 2500 words, the array will
not be sufficient.

Why This is an Issue:


You don't know the size of the text file beforehand, so
you can't determine the appropriate array size at the
start.
Creating an overly large array to accommodate the 3
Lists
• list: a collection storing an ordered sequence of
elements
– each element is accessible by a 0-based index
– a list has a size (number of elements that have been
added)
– elements can be added to the front, back, or elsewhere
– in Java, a list can be represented as an ArrayList object

4
A list is a collection that stores an ordered sequence of elements. Each element in
the list can be accessed and manipulated using its position, which is determined by a
0-based index (i.e., the first element is at index 0, the second at index 1, and so on).

ordered Sequence:
The elements in a list maintain the order in which they were added. This order is
preserved unless explicitly changed (e.g., by sorting or modifying the list).
Index-Based Access:
Each element is accessible by its index. For example:
list.get(0); // Retrieves the first element
Dynamic Size:
A list has a size that represents the number of elements it contains. Unlike arrays, the
size of a list can dynamically grow or shrink as elements are added or removed.
Insertion Flexibility:
Elements can be added:
To the front (index 0)
To the back (end of the list)
5
To a specific position (any valid index)
Idea of a list
• Rather than creating an array of boxes, create an
object that represents a "list" of items. (initially an
empty list.)
[]
• You can add items to the list.
– The default behavior is to add to the end of the list.
[hello, ABC, goodbye, okay]

• The list object keeps track of the element values that


have been added to it, their order, indexes, and its total
size.
– Think of an "array list" as an automatically resizing array
object.
6
Start with an empty list:
Imagine the list as an empty container where you can store
items.
Initially, it looks like this:
[]
Add items to the list:
You can add items to the list one by one. By default, new items
are added to the end of the list.
Example:
list.add("hello");
list.add("ABC");
list.add("goodbye");
list.add("okay");

7
What the list tracks for you:
The list automatically keeps track of:
The values of the items (e.g., "hello", "ABC").
The order of the items (they remain in the order you added them).
The index of each item (e.g., "hello" is at index 0, "ABC" is at index
1, and so on).
The total size of the list (how many items it contains).

Internally, how it works:


The list is built using an array.
If the array runs out of space when adding more items, the list
automatically resizes itself to make room for new items.
You don’t have to worry about how much space it needs—it
manages that for you.

8
Think of an "array list" as a smart, flexible array that
automatically grows as needed and keeps track of the
items, their order, and how many items there are. You
just add items and let it handle the details for you!

9
Type Parameters
(Generics)
ArrayList<Type> name = new ArrayList<Type>();

• When constructing an ArrayList, you must specify the


type of elements it will contain between < and >.
– This is called a type parameter or a generic class.
– Allows the same ArrayList class to store lists of different
types.
– Can store arraylist of String, Student, Sprite, Car objects,
etc…

ArrayList<String> names = new ArrayList<String>();


names.add("Marty Stepp");
names.add("Stuart Reges");
//notice the difference between arraylist & array10
ArrayList methods (10.1)
boolean add(E obj) appends obj at end of list, returns true
void add(int index, inserts given obj just before the given
E obj) index, shifting subsequent values to the
right
E get(int index) returns the element at given index
E remove(int index) removes/returns value at given index,
shifting subsequent values to the left
void remove(E obj) remove by object(Not on AP, but useful for
some of our labs.
E set(int index, replaces value at given index with given
E obj) value, returns element that was
previously at index.
int size() returns the number of elements in list
toString() returns a string representation of the list
Note: E refers to the type of objects in the arraylist.
such as "[3, 42, -7, 15]"
ArrayList class is part of the java.util package.
11
To use ArrayList: import java.util.*;
Add to end: Put a book on top.
Add at position: Insert a book at a specific spot.
Get by position: Look at a specific book.
Remove by position: Take a book out and fill the gap.
Remove by value: Search for a book and remove it.
Replace: Swap one book for another.
Size: Count how many books there are.
To String: Write down all the books as a list.

12
boolean add(E obj)
Description: Adds an element to the end of the list. Returns true if successful.
import java.util.ArrayList;

public class Main {


public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();

// Add elements to the list


list.add(10); // Adds 10 to the list
list.add(20); // Adds 20 to the list
System.out.println("After add: " + list); // Output: [10, 20]
}
}

void add(int index, E obj)


Description: Inserts an element at the specified index, shifting elements to the right.
// Insert an element at index 0
list.add(0, 5); // Adds 5 at index 0
System.out.println("After add at index: " + list); // Output: [5, 10, 20]

13
E get(int index)
Description: Returns the element at the specified index.

// Get the element at index 1


int value = list.get(1); // Gets the value at index 1
System.out.println("Value at index 1: " + value); // Output: 10

E remove(int index)
Description: Removes and returns the element at the specified index, shifting elements to the
left.
// Remove the element at index 0
int removed = list.remove(0); // Removes the element at index 0
System.out.println("Removed value: " + removed); // Output: 5
System.out.println("After remove: " + list); // Output: [10, 20]

void remove(E obj)


Description: Removes the first occurrence of the specified element by value.
// Remove the element with value 10
list.remove((Integer) 10); // Removes the value 10
System.out.println("After remove by value: " + list); // Output: [20]
14
E set(int index, E obj)
Description: Replaces the element at the specified index with the new value.
Returns the old value.
// Replace the element at index 0
int oldValue = list.set(0, 30); // Replaces 20 with 30
System.out.println("Replaced value: " + oldValue); // Output: 20
System.out.println("After set: " + list); // Output: [30]

7. int size()
Description: Returns the number of elements in the list.
// Get the size of the list
int size = list.size();
System.out.println("Size of the list: " + size); // Output: 1

toString()
Description: Returns a string representation of the list.
// Print the list as a string
System.out.println("List as a string: " + list); // Output: [30]
}
}
15
After add: [10, 20]
After add at index: [5, 10, 20]
Value at index 1: 10
Removed value: 5
After remove: [10, 20]
After remove by value: [20]
Replaced value: 20
After set: [30]
Size of the list: 1
List as a string: [30]

16
17
18
import java.util.ArrayList;

public class Main {


public static void main(String[] args) {
// Create an ArrayList of Strings
ArrayList<String> list = new ArrayList<>();

// Add elements to the list


list.add("Apple");
list.add("Banana");

// Remove the first occurrence of "Apple"


list.remove("Apple");

// Print the updated list


System.out.println(list); // Output: [Banana]
}
}

19
import java.util.ArrayList;

public class Main {


public static void main(String[] args) {
// Create an ArrayList of Strings
ArrayList<String> list = new ArrayList<>();

// Add an element to the list


list.add("Apple");

// Replace the element at index 0 with "Orange"


list.set(0, "Orange");

// Print the updated list


System.out.println(list); // Output: [Orange]
}
}

20
import java.util.ArrayList;

public class Main {


public static void main(String[] args) {
// Create an ArrayList of Strings
ArrayList<String> list = new ArrayList<>();

// Add elements to the list


list.add("Apple");
list.add("Banana");

// Print the size of the list


System.out.println(list.size()); // Output: 2
}
}

21
import java.util.ArrayList;

public class Main {


public static void main(String[] args) {
// Create an ArrayList of Strings
ArrayList<String> list = new ArrayList<>();

// Add elements to the list


list.add("Apple");
list.add("Banana");

// Print the string representation of the list


System.out.println(list.toString()); // Output: [Apple, Banana]
}
}

22
ArrayList vs. array
• construction
String[] names = new String[5];
ArrayList<String> list = new ArrayList<String>();

• storing a value
names[0] = "Jessica";
list.add("Jessica");

• retrieving a value
String s = names[0];
String s = list.get(0);

23
Construction

Array: Fixed size, requires you to specify the


size upfront.
ArrayList: Dynamic size, grows as elements are
added.

// Constructing an array of size 5


String[] names = new String[5];

// Constructing an ArrayList with no fixed size


ArrayList<String> list = new ArrayList<String>();

Explanation:

String[] names = new String[5];: Creates an


array that can store exactly 5 elements.
ArrayList<String> list = new ArrayList<String>();:
Creates an ArrayList that can grow and shrink
dynamically.

24
Storing a Value

Array: Use an index to store a value at a specific position.


ArrayList: Use the add method to append a value to the list.
// Storing a value in an array
names[0] = "Jessica";

// Storing a value in an ArrayList


list.add("Jessica");
Explanation:
names[0] = "Jessica";: Puts "Jessica" in the first slot of the array.
list.add("Jessica");: Appends "Jessica" to the end of the ArrayList.

Retrieving a Value

Array: Use the index directly to get a value.


ArrayList: Use the get method to access a value at a specific position.
// Retrieving a value from an array
String s = names[0];

// Retrieving a value from an ArrayList


String s = list.get(0);
Explanation:

String s = names[0];: Retrieves the value at index 0 in the array.


String s = list.get(0);: Retrieves the value at index 0 in the ArrayList. 25
ArrayList vs. array
ArrayList<String> list = new ArrayList<String>();

list.add(“Michael”);
list.add(“Jessica”);
list.add(“Lee”); //{“Michael”, “Jessica”, “Lee”}
list.add(1,“Sarah”);//{“Michael”, “Sarah”,”Jessica”, “Lee”}
String store=list.set(2,”Mary”)
//{Michael,Sarah,Mary,Lee}, store=“Jessica”

String store2=list.get(3);//store2=“Lee”

String store3=list.remove(1);
//{Michael,Mary,Lee}, store3=“Sarah”
Key Points to Remember:
add(): Appends to the end or inserts at a specific index (shifting elements to the
right).
set(): Replaces an element at a specific index and returns the old value.
get(): Retrieves the element at a specific index.
remove(): Removes the element at a specific index, returns it, and shifts subsequent
elements to the left. 26
Traversing an Arraylist
It is common to use for loops to access arraylist elements. This is
called
traversing the arraylist.

The list arrayList below is an arrayList of Strings from the previous


slides.

for (int i = 0; i < list.size(); i++) {


System.out.println(list.get(i));
}

Contrast this with an array also called list.

for (int i = 0; i < list.length; i++) {


System.out.println(list[i]);
}

27
28
29
Traversing an Arraylist
We can use a for each loop traverse the arraylist. The list arrayList
below is
an arrayList of Strings from the previous slides.

for (String name: list) {


System.out.println(name);
}

Note this syntax is the same for both arrays and arraylists!

Do not use the enhanced for each loop if you want to add or remove
elements when traversing a list because it will throw
a ConcurrentModificationException error. Since for each loops
do not use
an index, you cannot do this special case of incrementing only if it is
changed.

So if you are going to add or remove items or you need the index, 30
Common Error:Remove
Items
Removing an element from an arraylist requires care as elements
are shifted
left.

// Suppose allWords is an arraylist of words entered by


// user. Remove all words of length 3 from allWords.

for (int i = 0; i < allWords.size(); i++) {


String word = allWords.get(i);
if (word.length() == 3) {
allWords.remove(i);

}
}
This is an error! Once a word is removed, words are shifted to the
left, this will cause the next word to be skipped!
31
Remove Words
One way to fix the previous error is add a i-- correction.

// Suppose allWords is an arraylist of words entered by


// user. Remove all words of length 3 from allWords.

for (int i = 0; i < allWords.size(); i++) {


String word = allWords.get(i);
if (word.length() == 3) {
allWords.remove(i);
i--; //corrected
}
}

Can you think of another way of fixing this error?

32
Remove Words
Or alternatively, we can traverse the array backwards; this
eliminates the
need to do i--. Do you see why the following works?

// Suppose allWords is an arraylist of words entered by


// user. Remove all words of length 3 from allWords.

for (int i = allWords.size() - 1; i >= 0; i--) {


String word = allWords.get(i);
if (word.length() == 3) {
allWords.remove(i);
// i-- not needed!
}
}

33
ArrayList as parameter
A method can accept an arraylist as a parameter.
public static void name(ArrayList<Type> name) {

Write a method that count all of the letters in all of the Strings from
an
ArrayList of Strings.

public static int countLetters(ArrayList<String> list) {


int count = 0;
for (int i = 0; i < list.size(); i++) {
count += list.get(i).length();
}
return count;
}

34
ArrayList as parameter

Using for each:

public static int countLetters(ArrayList<String> list) {


int count = 0;
for (String item : list) {
count += item.length();
}
return count;
}

35
Returns an ArrayList
You can also return a list:
public static ArrayList<Type> methodName(params)

Write a method that accepts an array of String and return an


arraylist copy of
the array.
public static ArrayList<String> copy(String[] array)
{
ArrayList<String> result = new ArrayList<String>();

for (int i = 0; i < array.length; i++) {


result.add(array[i]);
}
return result;
}
36
ArrayList of primitives?
• The type you specify when creating an ArrayList must
be an object type; it cannot be a primitive type.
// illegal -- int cannot be a type parameter
ArrayList<int> list = new ArrayList<int>();
• But we can still use ArrayList with primitive types by
using wrapper classes in their place.
// creates a list of ints
ArrayList<Integer> list = new ArrayList<Integer>();
• Once you construct the list, use it with primitives as normal:
ArrayList<Double> grades = new ArrayList<Double>();
grades.add(3.2); //autoboxing
grades.add(2.7);
double myGrade = grades.get(0);//auto-unboxing

37
ArrayList of Integers

ArrayList<Integer> myList = new ArrayList<Integer>();


myList.add(50);
myList.add(30);
myList.add(20);

int total = 0;
for (int i = 0; i < myList.size(); i++){
total += myList.get(i);
}
System.out.println(total);

Output: 100

38
ArrayList "mystery"
ArrayList<Integer> list = new ArrayList<Integer>();

for (int i = 1; i <= 10; i++) {


list.add(10 * i);
}
What is in the arraylist list?
Answer: [10, 20, 30, 40, ..., 100]

for (int i = 0; i < list.size(); i++) {


list.remove(i);
}
System.out.println(list);
Answer: [20, 40, 60, 80, 100]

39
Out-of-bounds
• Legal indexes are between 0 and the list's size() - 1.
– Reading or writing any index outside this range will cause
an IndexOutOfBoundsException.

ArrayList<String> names = new ArrayList<String>();


names.add("Marty"); names.add("Kevin");
names.add("Vicki"); names.add("Larry");
System.out.println(names.get(0)); // okay
System.out.println(names.get(3)); // okay
System.out.println(names.get(-1)); // exception
names.add(9, "Aimee"); // exception

inde 0 1 2 3
x
valu Mart Kevi Vic Larr
e y n ki y 40
ArrayList "mystery" 2
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 5; i++) {
list.add(2 * i); // [2, 4, 6, 8, 10]
}

What is the output of the following code?


for (int i = 0; i < list.size(); i++) {
list.add(i, 42); // add 42 at index i
}
System.out.println(list);

Answer: Infinite Loop!

41
ArrayList "mystery" 3
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 5; i++) {
list.add(2 * i); // [2, 4, 6, 8, 10]
}

What is the output of the following code?


int size = list.size();
for (int i = 0; i < size; i++) {
list.add(i, 42); // add 42 at index i
}
System.out.println(list);

Answer:
[42, 42, 42, 42, 42, 2, 4, 6, 8, 10]

42
Objects storing
collections
• An object can have an array, list, or other collection as
a field.

public class Course {

private ArrayList<Student> students;

public Course() {
students = new ArrayList<Student>();
...
}

• Now each object stores a collection of data inside it.

43
Lab 1
Write the following static methods.

•Write the method smallest which accepts an arraylist of


integers and return the smallest. Your return type should be
an Integer. MUST USE a for each loop.

•Write the method longest which accepts an arraylist of


strings and return the longest string. Return the first one if
there are multiple longest strings. MUST USE a regular for
loop.

•Write the method remove which accepts an arraylist of


Integers list and an integer variable x. Remove all
occurrences of x in list.
44
Lab 2(Processing)
A random set of coins are placed randomly on the screen. The
tank moves around and collect the coins. A template for this
lab with comments explaining the lab is available on my
website here.

Here is the link to slides


that explain how to do
collision detection.

45
Lab 3(Processing)
Tank Shooting Lab: Download the template for this processing
lab on my website.

Tank shoots bullets.


Crate is removed if
hit by a bullet.

Score keeps track


of number of
crates hit.

46

You might also like