Relevant Notes: CS1400 - Arrays
// Reference variable
int[] numbers; // (undefined, NOT null)
// Create array
numbers = new int[6]; // Remember, arrays are objects!Array: Indexed list of data elements.
null, numeric fields become 0.NULL or a length of 0 won’t result in syntax error, you’ll have o check that yourself)Note:
length
- Arrays have an immutable (
final) field calledlength.
- Everywhere else, length is usually a method (e.g.,
string.length())System.out.println("Array Length: " + numbers.length);
Examples: Initialization
// Using an initialization list int[] days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // Using a bunch of individual statements days[0] = 31; days[1] = 28; days[2] = 31; days[3] = 30; days[4] = 31; days[5] = 30;
Examples: Declaration
int[] numbers; int numbers[]; int[] numbers, codes, scores; int numbers[], codes[], scores[];
Note: Partially-Filled Arrays
- Typically, if the amount of data is variable, but the largest expected number is known, we can allocate a large array and use a counter variable to keep track of how much valid data is in the array.
- We might also use an
ArrayList.
Copying by Value
int[] x = { 1, 2, 3 };
int[] y = new int[x.length];
for (int i = 0; i < x.length; i++)
y[i] = x[i];Compare by Value
array1 == array2 will just compare two addresses. To compare each element by value you’ll want to iterate.int[] x = { 1, 2, 3 };
int[] y = { 1, 2, 3 };
if (x.length != y.length)
return false;
int i = 0;
while (i < x.length)
if (x[i] != y[i])
return false;
i++;
return true;ArrayIndexOutOfBoundsException)Accessing an invalid index will result in an unchecked (runtime) exception.
for (datatype elementVariable : array)
statement;int[] numbers = {3, 6, 9};
// Enhanced (read-only)
for (int x : numbers) {
System.out.println(x);
}
// Traditional (read/write)
for (int i = 0; i < numbers.length; i++)
{
System.out.println(numbers[i]);
}Two-Dimensional Arrays: Array of arrays.
// Make a ragged array
int[][] matrix;
matrix = new int[5][];
for (int i = 0; i < matrix.length - 1; i++) {
matrix[i] = new int[i];
}Note: ragged arrays are easier to do in Java because memory allocation is handled for us and everything is objects.
- In other languages we might have to fiddle with memory and pointers.
- In Java, we don’t have to worry about whether data is being stored row or column-wise in memory.
// Make a ragged array
int[][] matrix;
matrix = new int[5][];
for (int i = 0; i < matrix.length - 1; i++) {
matrix[i] = new int[i];
}Sorting: Process of arranging a list of items in a particular order.
Important:
str1.compareTo(str2)
- Returns
0if str1 equal to str2- Returns
<0if the str1 is lexicographically less than str2- Returns
>0if the str1 is lexicographically greater than str2
Process:
Efficiency:
Note on Swapping: Swapping requires 3 assignment statements and a temporary storage location.
Process:
Efficiency:
Searching: Processor of finding a target element within a group of items called the search pool.
Process:
Performance:
Example:
public static int sequentialSearch(int[] array, int value) {
int index = 0;
int element = -1;
boolean found = false;
while (!found && index < array.length) {
if (array[index] == value) {
found = true;
element = index;
}
index++;
}
return element;
}Process:
Performance:
Example:
public static int binarySearch(int[] array, int value)
{
int first; last, middle, position;
boolean found = false;
first = 0;
last = array.length - 1;
position = -1;
while (!found && first <= last) {
middle = (first + last) / 2;
if (array[middle] == value) {
found = true;
position = middle;
}
else if (array[middle] > value)
last = middle - 1;
else
first = middle + 1;
}
return position;
}Header:
public static void main(String[] args)Important: Remember to parse strings into numeric values if you want to use numeric values!
public class args {
public static void main(String[] args) {
int i = 0;
for (String x : args) {
System.out.println(i + ": " + x);
i++;
}
}
}$ javac args.java && java args Hello there!
0: Hello
1: there!vararg: Special type parameter.
Printf actually uses Object... vararg.public static int sum (int... numbers) {
int sum = 0;
for (int x : numbers)
sum += x;
return sum;
}%n)UNIX newlines are \n, DOS newlines are \n\r.
In printf you can use %n to print newlines compatible with the current operating system.
Unlike an array, ArrayList automatically expands and shrinks when items are added and removed.
Integer instead of int).Capacity: Number of items the ArrayList can store without increasing its size.
Import:
import java.util.ArrayList;Create:
// Create string ArrayList with default capacity 10
ArrayList<String> nameList = new ArrayList<>();
// Create string ArrayList with capacity 100
ArrayList<String> nameList = new ArrayList<>(100);new ArrayList<>();)ArrayList<String> nameList)Common Methods:
.add().size().get().toString().remove().set()Note: Since
.toString()is implicitly called, you can doSystem.out.println(nameList);for easy debugging.
Example
import java.util.ArrayList;
public class list {
public static void main(String[] args) {
ArrayList<String> nameList = new ArrayList<>();
nameList.add("Bob");
nameList.add("Alice");
nameList.add(0, "Bingus");
nameList.remove(2);
nameList.set(1, "Dingus");
System.out.println("nameList: " + nameList);
}
}$ javac list.java && java list
nameList: [Bingus, Dingus]