ONE DIMENSIONAL ARRAYS:
• In Java, an array is declared with fixed length that cannot be changed.
• In Java, an index is written within square brackets following array’s name (for example, a[k]).
• Indices start from 0; the first element of an array a is referred to as a[0] and the n-th element as a[n-1].
• An index can have any int value from 0 to array’s length - 1.
• Java interpreter checks the values of indices at run time and throws ArrayIndexOutOfBoundsException if an index is negative or if it is greater than the length of the array - 1.
Arrays can be declared and initialized in one statement (See 2,3, and 4)
1. int [ ] scores = new int [10] ; // declares an integer array of size 10 called “scores”
2. private double [ ] gasPrices = { 3.05, 3.17, 3.59 };
3. String [ ] words = new String [10000];
4. String [ ] cities = {"Atlanta", "Boston", "Cincinnati" };
Note: The array scores has not been initialized and refers to a null object.
Length:
public int length is a public field in the array class. To call the length field, use the dot operator
i.e. array.length; (notice it is not a method so no parentheses)
Default Values:
Unless specific values are given in a {…} list, all the elements are initialized to the default value: 0 for numbers, false for booleans, null for objects.
Note: Remember if you use a method on a null object you will get a null-pointer exception at runtime.
Initializing:
String [] words = new String[3];
words[0] = “APCS”;
words[1] = “is”;
words[2] = “hard”;
OR:
String[] words = {“APCS”, “is” , “hard”};
Passing Arrays to methods:
• As other objects, an array is passed to a method as a reference.
• The elements of the original array are not copied and are accessible in the method’s code.
Returning Arrays from methods:
• As any object, an array can be returned from a method.
• i.e. public double[] getNumbers() //returns an array of double type numbers
Practice CodingBat Array 1 and Array 2!!!!!!!!!
For Each Loop (Good for arrays and ArrayLists)
int [ ] scores = { ... };
...
int sum = 0;
for (int s : scores)
{
sum += s;
}
The For Each Loop does the Same as the following:
for (int i = 0; i < scores.length; i++)
{
sum += scores[i];
}
• Notes: You cannot add or remove elements within a “for each” loop.
• You cannot change elements of primitive data types or references to objects within a “for each” loop.
TWO-DIMENSIONAL ARRAYS
A two-dimensional array is really an array of arrays.
i.e. String[][] ticTac = {{“X”, “X”, “O”}, {“O”, “O”, “X”}, {“X”, “O”, “X”}};
Visually you can think of two-dimensional arrays the same way as a matrix, with rows and columns.
X X O
O O X
X O X
Another way of assigning values to a 2-D array is similar to how we did with 1-D arrays.
i.e. String[][] ticTac = new String[3][3];
ticTac[0][0] = “X”;
ticTac[0][1] = “X”;
ticTac[0][2] = “O”;
Remember: ROW then COLUMN
ticTac[1] refers to {“O”, “O”, “X”}
Length:
ticTac.length refers to how many rows there are (how many “inside arrays”)
ticTac[1].length refers to how many elements are in the first “inside array” (i.e. how many columns are in row 1)
*All arrays in APCS should be rectangular so ticTac[i].length should be the same for all i rows
For 2-D array above (called arr): arr.length = 4 and arr[0].length = 5
Reminder: there are rows 0,1,2,3 and columns 0,1,2,3,4 - if you talk about row 4 (even though there are 4 rows), you will get an out-of-bounds exception.
Traversing through a 2-D array:
Use a nested loop: The following accesses every element of the 2-D array
for (int r = 0; r < m.length; r++)
{
for (int c = 0; c < m[0].length; c++)
{
... // process m[ r ][ c ]
}
}
Triangular Loops: Good test question. What does this do?
int n = m.length;
for (int r = 1; r < n; r++)
{
for (int c = 0; c < r; c++)
{
double temp = m [ r ][ c ];
m [ r ][ c ] = m [ c ][ r ];
m [ c ][ r ] = temp;
}
}
Array Lists:
• Keeps track of the list capacity (the length of the allocated array) and list size (the number of elements currently in the list)
1. Capacity is the length of the array. The default capacity is 10 (from the default constructor: new ArrayList<Type>())
2. The capacity is automatically doubled if it runs out of space.
3. size() is a method that keeps track of the number of elements in the list.
• Can only hold objects (of a specified type), not elements of primitive data types.
Syntax:
ArrayList<String> words = new ArrayList<String>();
creates an ArrayList with size 0.
*We use the add() method to put elements into the ArrayList.
Methods:
int size()
boolean isEmpty()
boolean add(E obj) – adds obj to the end of the list and returns true.
void add(int i, E obj) – adds obj as the i-th value (i must be from 0 to size())
*add shifts the objects at and above i to the right
E set(int i, E obj) – sets obj as the i-th value
*removes the object that was there and returns it
* i must be from 0 to size() - 1
E get(int i) – returns the obj at the i-th value
* i must be from 0 to size() - 1
E remove(int i) – removes and returns the object at the i-th value
* i must be from 0 to size() – 1
boolean contains(E obj)- returns true if the ArrayList contains obj
*automatically calls the equal method from the Object class
int indexOf(E obj) – returns the first index of an object that equals obj
**Both contains and indexOf methods use the equals method.
AutoBoxing and UnBoxing:
As mentioned ArrayLists only can contain objects so if we wanted to use an ArrayList of ints or doubles we would have to use the wrapper classes:
Integer and Double.
The main focus of these methods is to wrap a number that is a primitive type (i.e. int or double) into an object (Integer or Double)
Methods:
Double valueOf(double d)
double doubleValue()
These methods would box a double d into a Double object and unbox a Double object into a double.
The same methods are in the Integer class as well as Integer.parseInt(String number)
*******Luckily Java 5 auto boxes and unboxes for us so we never have to worry about using these methods in an ArrayList.
Example 1:
ArrayList<Double> nums = new ArrayList<Double>();
nums.add(6.3);
creates an ArrayList of doubles and adds a Double object with value 6.3 into the list.
Example 2 (Using some methods)
ArrayList<String> words = new ArrayList<String>();
words.add(“Mr.”);
words.add(“Sapp”);
words.add(“is a”);
words.add(“terrible”);
words.add(“teacher”);
words.add(3, “not-so”);
words.set(1, “Snope”);
System.out.println(words.get(4)); //would print terrible
System.out.println(words);
// would print {“Mr.” , “Snope”, “is a”, “not-so”, “terrible”, “teacher”}
ArrayList PitFall:
The problem is that the words in the words ArrayList will be shifted down once an element is removed. When i is incremented, it will skip the next word in the list. How can we fix it???