31
Java Chapter 7: Arrays and Array Lists Slides material compiled from Big Java 4 th Edition By Cay Hortsmann

Java Chapter 7: Arrays and Array Lists

  • Upload
    others

  • View
    21

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Java Chapter 7: Arrays and Array Lists

Java Chapter 7: Arrays and

Array Lists

Slides material compiled from Big Java 4th Edition

By Cay Hortsmann

Page 2: Java Chapter 7: Arrays and Array Lists

Arrays

• Array: sequence of values of the same type

• To construct an array of 10 integers

int[] values = new int[10];

– values is a reference to array of integers

• Can also form arrays of objects

BankAccount[] accounts = new BankAccount[10];

Rakhi Saxena (Internet Technologies) 2

Page 3: Java Chapter 7: Arrays and Array Lists

Initializing Arrays

• At time of creation, all elements are initialized with

– 0 (for an array of numbers such as int[] or double[] )

– false (for a boolean[] array), or

– null (for an array of object references)

• Possible to initialize an array with other values int[] primes = { 2, 3, 5, 7, 11 };

Rakhi Saxena (Internet Technologies) 3

Page 4: Java Chapter 7: Arrays and Array Lists

Declaring Arrays

Rakhi Saxena (Internet Technologies) 4

Page 5: Java Chapter 7: Arrays and Array Lists

Initializing/ Modifying Arrays

• Each element in the array is specified by an integer index values[2] =29.95;

System.out.println("The element at

index 2 is " + values[2]);

• Note: array index values start at 0 • Index values of an array range from 0 to length – 1 • Accessing a nonexistent element results in a bounds error. • The expression array.length yields the number of elements in an

array (length is a final public instance variable)

Rakhi Saxena (Internet Technologies) 5

Page 6: Java Chapter 7: Arrays and Array Lists

Common Errors - Bounds Errors

• Attempting to access a nonexistent position

double[] data = new double[10];

data[10] = 29.95;

// Error—can access only index 0 . . . 9

• When the program runs, an out-of-bounds index generates an exception and terminates the program

Rakhi Saxena (Internet Technologies) 6

Page 7: Java Chapter 7: Arrays and Array Lists

Common Errors Uninitialized and Unfilled Arrays

• Attempting to allocate an array reference, but not an actual array. double[] values;

values[0] = 29.95; // Error—values not initialized

– To construct the actual array, you must use the new operator:

double[] values = new double[10];

• Allocating an array of objects and expect it to be filled with objects. BankAccount[] accounts = new BankAccount[10];

// Contains ten null references

– Array contains null references, not default bank accounts

– Remember to fill the array,

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

accounts[i] = new BankAccount(); }

Rakhi Saxena (Internet Technologies) 7

Page 8: Java Chapter 7: Arrays and Array Lists

Array Lists

• ArrayList class – manages a sequence of objects whose size can change

– grow and shrink as needed

– supplies methods for many common tasks, such as inserting and removing elements

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

• ArrayList is called a generic class ArrayList<T> – T refers to any class

– cannot use primitive types (int/ double) as type parameters

Rakhi Saxena (Internet Technologies) 8

Page 9: Java Chapter 7: Arrays and Array Lists

Adding elements to an ArrayList • When an ArrayList object is constructed, its size = 0

• add method adds an object to the end of the array list; size increases after each call to add

names.add("Emily"); names.add("Bob");

names.add("Cindy");

Rakhi Saxena (Internet Technologies) 9

Page 10: Java Chapter 7: Arrays and Array Lists

Working with ArrayLists • To access an element, use the get method, not the [ ] operator String name = names.get(2);

• size method yields the current size of the array list int i = names.size();

• As with arrays, index values start at 0 name = names.get(i); //Error: The last valid

//index is names.size() – 1

• To set an array list element to a new value, use the set method names.set(2, “Carolyn”); //overwrite element

• Can also insert an object in the middle of an array list using add method at a given index, all elements are moved

names.add(1, “Ann”); // shift elements down

• To remove element at a given index use remove method names.remove(1); // shift elements up

Rakhi Saxena (Internet Technologies) 10

Page 11: Java Chapter 7: Arrays and Array Lists

Working with ArrayLists

Rakhi Saxena (Internet Technologies) 11

Page 12: Java Chapter 7: Arrays and Array Lists

BankAccount.java

Rakhi Saxena (Internet Technologies) 12

Page 13: Java Chapter 7: Arrays and Array Lists

BankAccount.java (contd.)

Rakhi Saxena (Internet Technologies) 13

Page 14: Java Chapter 7: Arrays and Array Lists

BankAccount.java (contd.)

Rakhi Saxena (Internet Technologies) 14

Page 15: Java Chapter 7: Arrays and Array Lists

BankAccount.java (contd.)

Rakhi Saxena (Internet Technologies) 15

Page 16: Java Chapter 7: Arrays and Array Lists

ArrayListTester.java

Rakhi Saxena (Internet Technologies) 16

Page 17: Java Chapter 7: Arrays and Array Lists

Common Error - Length and Size

Rakhi Saxena (Internet Technologies) 17

Page 18: Java Chapter 7: Arrays and Array Lists

ArrayList Syntax Enhancements in Java 7

• When declaring an array list, no need repeat the type parameter in the constructor

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

• Can supply initial values as follows ArrayList<String> names = new ArrayList<>(["Ann",

"Cindy", "Bob"]);

• Can access array list elements with the [] operator (Compiler translates the syntax)

String name = names[i];

//translated to String name = names.get(i);

names[i] = "Fred";

// translated to names.set(i, "Fred");

Rakhi Saxena (Internet Technologies) 18

Page 19: Java Chapter 7: Arrays and Array Lists

Wrappers Classes • To treat primitive type values as objects, have to use

wrapper classes • Eight wrapper classes for all primitive types

• Wrapper objects can be used anywhere that objects are required instead of primitive type values.

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

values.add(29.95);

double x = values.get(0);

Rakhi Saxena (Internet Technologies) 19

Page 20: Java Chapter 7: Arrays and Array Lists

Auto-Boxing

• Conversion between primitive types and the corresponding wrapper classes is automatic

Double d = 29.95; // Auto-boxing

// same as Double d = new Double(29.95);

• Conversely, wrapper objects are automatically “unboxed” to primitive types

double x = d; //Auto-unboxing

// same as double x = d.doubleValue();

• Auto-boxing even works inside arithmetic expressions d = d + 1;

Rakhi Saxena (Internet Technologies) 20

Page 21: Java Chapter 7: Arrays and Array Lists

The Enhanced for Loop • The enhanced for loop traverses all elements of a collection double[] values = . . .;

double sum = 0;

for (double element : values)

{

sum = sum + element;

}

ArrayList<BankAccount> accounts = . . . ;

double sum = 0;

for (BankAccount account : accounts)

{

sum = sum + account.getBalance();

}

Note: “for each” loop does not allow modification of array contents

Rakhi Saxena (Internet Technologies) 21

Page 22: Java Chapter 7: Arrays and Array Lists

Partially Filled Arrays

• With a partially filled array, keep a companion variable to track how many elements are used

final int VALUES_LENGTH = 100;

double[] values = new double[VALUES_LENGTH];

int valuesSize = 0;

Scanner in = new Scanner(System.in);

while (in.hasNextDouble())

{

if (valuesSize < values.length)

{ values[valuesSize] = in.nextDouble();

valuesSize++;

}

}

for (int i = 0; i < valuesSize; i++)

{ System.out.println(values[i]); }

Rakhi Saxena (Internet Technologies) 22

Page 23: Java Chapter 7: Arrays and Array Lists

Common Array Algorithms - Filling

• Fill an array with zeroes: for (int i = 0; i < values.length; i++)

{ values[i] = 0; }

• Fill an array list with squares (0, 1, 4, 9, 16, …) for (int i = 0; i < values.size(); i++)

{ values.set(i, i * i);}

Rakhi Saxena (Internet Technologies) 23

Page 24: Java Chapter 7: Arrays and Array Lists

Common Array Algorithms - Counting Matches

• To count values, check all elements and count the matches until the end of array

public class Bank {

private ArrayList<BankAccount> accounts;

public int count(double atLeast)

{ int matches = 0;

for (BankAccount account : accounts)

{

if (account.getBalance() >= atLeast) matches++;

// Found a match

}

return matches;

}

. . .

}

Rakhi Saxena (Internet Technologies) 24

Page 25: Java Chapter 7: Arrays and Array Lists

Common Array Algorithms - Finding the Maximum or Minimum

• To compute the maximum or minimum value, initialize a candidate with the starting element

• Then compare the candidate with the remaining elements and update it if you find a larger or smaller value

if (accounts.size() == 0) return null;

BankAccount largestYet = accounts.get(0);

for (int i = 1; i < accounts.size(); i++)

{ BankAccount a = accounts.get(i);

if (a.getBalance() > largestYet.getBalance())

largestYet = a;

}

return largestYet;

Rakhi Saxena (Internet Technologies) 25

Page 26: Java Chapter 7: Arrays and Array Lists

Common Array Algorithms - Searching for a Value

• To find a value, check all elements until you have found a match

public class Bank

{

. . .

public BankAccount find(int accountNumber)

{ for (BankAccount account : accounts)

{ if (account.getAccountNumber() == accountNumber)

return account; // Found a match

}

return null; // No match in the entire array list

}

. . .

}

Rakhi Saxena (Internet Technologies) 26

Page 27: Java Chapter 7: Arrays and Array Lists

Common Array Algorithms - Locating the Position of an Element

• Use a variation of the linear search algorithm, but remember the position instead of the matching element

int pos = 0;

boolean found = false;

while (pos < values.size() && !found)

{ if (values.get(pos) > 100)

{ found = true;}

else

{ pos++;}

}

if (found) {

System.out.println("Position: " + pos); }

else { System.out.println("Not found"); }

Rakhi Saxena (Internet Technologies) 27

Page 28: Java Chapter 7: Arrays and Array Lists

Common Array Algorithms - Removing an Element

• If the order of the elements does not matter, insert new elements at the end, incrementing the variable tracking the size

if (valuesSize < values.length)

{ values[valuesSize] = newElement;

valuesSize++;

}

• To insert an element at a particular position in the middle of an array, move all elements above the insertion location to a higher index and insert the new element

if (valuesSize < values.length)

{ for (int i = valuesSize; i > pos; i--)

{ values[i] = values[i - 1]; }

values[pos] = newElement;

valuesSize++;

}

Note: To insert an element into an array list, simply use the add method Rakhi Saxena (Internet Technologies) 28

Page 29: Java Chapter 7: Arrays and Array Lists

Common Array Algorithms - Removing an Element

• If the elements in the array are not in any particular order, simply overwrite the element to be removed with the last element of the array, then decrement the variable tracking the size of the array

values[pos] = values[valuesSize - 1];

valuesSize--;

• If the order of the elements matters, move all elements following the element to be removed to a lower index, and then decrement the variable holding the size of the array

for (int i = pos;i < valuesSize - 1; i++)

{ values[i] = values[i + 1];}

valuesSize--;

Rakhi Saxena (Internet Technologies) 29

Page 30: Java Chapter 7: Arrays and Array Lists

Common Array Algorithms - Copying and Growing Arrays

• An array variable stores a reference to the array. Copying the variable yields a second reference to the same array

double[] values = new double[6]; . . . // Fill array

double[] prices = values;

• Use the Arrays.copyOf method to copy the elements of an array values = Arrays.copyOf(values, 2 * values.length);

• Another use for Arrays.copyOf is to grow an array that has run out of space

int valuesSize = 0;

while (in.hasNextDouble())

{

if (valuesSize == values.length)

values = Arrays.copyOf(values, 2 * values.length);

values[valuesSize] = in.nextDouble();

valuesSize++;

} Rakhi Saxena (Internet Technologies) 30

Page 31: Java Chapter 7: Arrays and Array Lists

Common Array Algorithms - Printing Element Separators

• To display the elements of an array or array list, one usually wants to separate them, often with commas or vertical lines, like this:

Ann | Bob | Cindy • Note that there is one fewer separator than there are

elements. Print the separator before each element except the initial one (with index 0):

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

{

if (i > 0)

{ System.out.print(" | "); }

System.out.print(names.get(i));

}

Rakhi Saxena (Internet Technologies) 31