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

Array Lists

This document provides an overview of ArrayLists in Java. It describes ArrayLists as automatically resizing arrays that can grow and shrink as needed. It explains that ArrayLists use generics to specify the type of elements stored and maintain ordering. The document also summarizes key ArrayList methods like add, get, remove and contains; and covers concepts like type parameters, autoboxing/unboxing of primitives, and exceptions from accessing out-of-bounds indexes.

Uploaded by

haladaher5555
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Array Lists

This document provides an overview of ArrayLists in Java. It describes ArrayLists as automatically resizing arrays that can grow and shrink as needed. It explains that ArrayLists use generics to specify the type of elements stored and maintain ordering. The document also summarizes key ArrayList methods like add, get, remove and contains; and covers concepts like type parameters, autoboxing/unboxing of primitives, and exceptions from accessing out-of-bounds indexes.

Uploaded by

haladaher5555
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 20

ArrayList

Building Java Programs


Chapter 10
Data structure and algorithms
Chapter 6
Collections
• collection: an object that stores data; a.k.a. "data structure"
– the objects stored are called elements
– some collections maintain an ordering; some allow duplicates
– typical operations: add, remove, clear, contains (search), size

– examples found in the Java class libraries:


• ArrayList, LinkedList, HashMap, TreeSet, PriorityQueue

– all collections are in the java.util package


import java.util.*;

2
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

3
Idea of ArrayList<>
• ArrayList<E> where E indicates the type of items that will be
included in the ArrayList, is a class that lets you collect objects
just like an array does; but it has two significant conveniences:
− ArrayList can grow and shrink as needed (it is initially an empty list).
− ArrayList class supplies methods for many common tasks, such as
inserting and removing elements
• The default behavior is to add to the end of the list.

• ArrayList 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.
– Internally, the list is implemented using an array and a size field.

4
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.

• Example
ArrayList<String> names = new ArrayList<String>();
names.add("Marty Stepp");
names.add("Stuart Reges");
• When you construct an array list, it has a size 0
− The size increases every time an element is added to the array list
− The size method yields number of elements

5
ArrayList methods (10.1)
add(value) appends value at end of list
add(index, value) inserts given value just before the given index, shifting
subsequent values to the right
clear() removes all elements of the list
indexOf(value) returns first index where given value is found in list (-1 if not
found)
get(index) returns the value at given index
remove(index) removes/returns value at given index, shifting subsequent
values to the left
set(index, value) replaces value at given index with given value
size() returns the number of elements in list
toString() returns a string representation of the list
such as "[3, 42, -7, 15]"
contains(value) returns true if given value is found somewhere in this list
lastIndexOf(value) returns last index value is found in list (-1 if not found)
6
add and set methods
ArrayList<String> names = new ArrayList<String>();
System.out.println("Names = " + names);
names.add("Marty Stepp");
System.out.println(“Names = " + names);
names.add("Stuart Reges");
System.out.println("Names = " + names);
names.add(0, "Hello");
System.out.println("Names = " + names);
names.add(2, "and");
System.out.println("Names = " + names);
names.set(2, "or");
System.out.println("Names = " + names);

Output
• Names = []
• Names = [Marty Stepp]
• Names = [Marty Stepp, Stuart Reges]
• Names = [Hello, Marty Stepp, Stuart Reges]
• Names = [Hello, Marty Stepp, and, Stuart Reges]
• Names = [Hello, Marty Stepp, or, Stuart Reges] 7
get and remove methods

− Removing moves all elements after the removed element down by one position,
and reduces the size of the array list by 1

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


names.add("Marty Stepp");
names.add("Stuart Reges");
names.add(0, “Hello");
names.add(2, “and");
names.set(2, “or");
System.out.println(“Names = ” + names);
System.out.println(names.get(2));
names.remove(2);
System.out.println(names.get(2));
System.out.println(“Names = ” + names);

Output
Names = [Hello, Marty Stepp, or, Stuart Reges]
Or
Stuart Reges
Names = [Hello, Marty Stepp, Stuart Reges]
8
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);

• seeing whether the value "Benson" is found


for (int i = 0; i < names.length; i++) {
if (names[i].equals("Benson")) { ... }
}
if (list.contains("Benson")) { ... } 9
Searching Methods
• Suppose that file of names which has some duplicates. You want to
write a program that gets rid of the duplicates.
Maria Derek Erica
Livia Jack Anita
Kendal Maria Livia Derek
Jamie Jack
Erica
ArrayList<String> list = new ArrayList<String>();
Scanner input = new Scanner(new File("words.txt"));
while (input.hasNext()) {
String name= input.next();
if (!list.contains(name) {
list.add(name);
}
}
System.out.println("list = " + list);

Output
List = [Maria, Derek, Erica, Livia, Jack, Anita, Kendal, Jamie]
10
ArrayList as parameter
public static void name(ArrayList<Type> name) {
• Example:
//search for a string target and replace it with replacement
public static void replace (ArrayList<String> list,
String target, String replacement){
int index = list.indexOf(target);
if (index>=0){
list.set(index, replacement)
}
}

• You can also return a list:


public static ArrayList<Type> methodName(params)

11
ArrayList of primitives?
• The type you specify when creating an ArrayList must be an
object type; it cannot be a primitive type.
– You cannot insert primitive types directly into array lists
// illegal -- int cannot be a type parameter
ArrayList<int> list = new ArrayList<int>();

• But we can still use ArrayList with primitive types by using


special classes called wrapper classes in their place.
• A wrapper is an object whose sole purpose is to hold a primitive
value.

// creates a list of ints


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

12
Wrappers

ArrayList<Double> data = new ArrayList<Double>();


data.add(29.95);
double x = data.get(0);
Double d = 29.95; // auto-boxing; same as Double d = new
Double(29.95);
13
double x = d; // auto-unboxing; same as double x = d.doubleValue();
Wrapper classes and Generalized for
• Traverses all elements of a collection:

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


list.add(13);
list.add(47); //autoboxing
list.add(9);
int sum = 0;
for (int n : list) // You should read this loop as "for each n in list"
{
sum = sum + n; //unboxing
}
System.out.println(“list =“ + list);
System.out.println(“sum =“ + sum);

Another unboxing example


int product = list.get(0)*list.get(1) ;

14
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

index 0 1 2 3

value Marty Kevi Vick Larry


n i
15
Complete Example
for you to read and execute
// Each BankAccount object represents account information for a bank customer.
// We use private fields and public methods to make sure that the user
// cannot ever have a negative account balance.

import java.util.*; // for ArrayList


public class BankAccount {
// An object can have an array list, or other collection as a field.
private int id;
private double balance;
private ArrayList<String> transactions;

// Constructs a new account with the given ID and a balance of $0.00.


public BankAccount(int accountID) {
id = accountID;
balance = 0.0;
transactions = new ArrayList<String>();
}
16
Complete Example
// Deposits the given amount of money into the user's account.
// If the deposit amount is too big (more than $500), or if it is
// negative, the method does nothing.
// Also records a log entry of the deposit to be printed later.
public void deposit(double money) {
if (0 <= money) {
balance = balance + money;
transactions.add("Deposit of $" + money);
}
}

17
Complete Example
// Withdraws the given amount of money from the user's account.
// If the user does not have enough money, or if the amount of money is negative, the
// method does nothing. Also records a log entry of the withdrawal to be printed later.
public void withdraw(double money) {
if (0 <= money && money <= balance) {
balance = balance - money;
transactions.add("Withdrawal of $" + money);
}
}
// Returns the account user's current balance.
public double getBalance() {
return balance;
}
// Returns the account user's ID number.
public double getID() {
return id;
} 18
Complete Example
// Prints a log of all transactions (deposits and withdrawals) that have
// been made on this account, one per line.
public void printLog() {
for (int i = 0; i < transactions.size(); i++) {
String element = transactions.get(i);
System.out.println(element);
}
}
}

19
Complete Example -Test Program
// This 'client' program uses a BankAccount object and calls
// the printLog method we wrote in class.
public class UseAccount {
public static void main(String[] args) {
BankAccount marty = new BankAccount(19);
marty.deposit(7.84);
marty.withdraw(2.53);
marty.deposit(6.19);
marty.deposit(2.58);
marty.withdraw(999.99); // should fail (no transaction log)

marty.printLog();
System.out.println();

marty.withdraw(4.18);
marty.deposit(-123.45); // should fail (no transaction log)
marty.printLog();
}
20
}

You might also like