Upload
others
View
21
Download
0
Embed Size (px)
Citation preview
Java Chapter 7: Arrays and
Array Lists
Slides material compiled from Big Java 4th Edition
By Cay Hortsmann
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
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
Declaring Arrays
Rakhi Saxena (Internet Technologies) 4
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
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
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
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
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
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
Working with ArrayLists
Rakhi Saxena (Internet Technologies) 11
BankAccount.java
Rakhi Saxena (Internet Technologies) 12
BankAccount.java (contd.)
Rakhi Saxena (Internet Technologies) 13
BankAccount.java (contd.)
Rakhi Saxena (Internet Technologies) 14
BankAccount.java (contd.)
Rakhi Saxena (Internet Technologies) 15
ArrayListTester.java
Rakhi Saxena (Internet Technologies) 16
Common Error - Length and Size
Rakhi Saxena (Internet Technologies) 17
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
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
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
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
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
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
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
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
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
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
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
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
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
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