Relevant Notes: CS1400 - Arrays
// Reference variable
int[] numbers; // (undefined, NOT null)
// Create array
= new int[6]; // Remember, arrays are objects! numbers
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 [0] = 31; days[1] = 28; days[2] = 31; days[3] = 30; days[4] = 31; days[5] = 30; days
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++)
[i] = x[i]; y
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;
++;
ireturn true;
ArrayIndexOutOfBoundsException
)Accessing an invalid index will result in an unchecked (runtime) exception.
for (datatype elementVariable : array)
; statement
Example: Enhanced for loop
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.
Example: 2d ragged array
// Make a ragged array int[][] matrix; = new int[5][]; matrix for (int i = 0; i < matrix.length - 1; i++) { [i] = new int[i]; matrix}
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.
Example: 2d ragged array
// Make a ragged array int[][] matrix; = new int[5][]; matrix for (int i = 0; i < matrix.length - 1; i++) { [i] = new int[i]; matrix}
Sorting: Process of arranging a list of items in a particular order.
Important:
str1.compareTo(str2)
- Returns
0
if str1 equal to str2- Returns
<0
if the str1 is lexicographically less than str2- Returns
>0
if 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) {
= true;
found = index;
element }
++;
index}
return element;
}
Process:
Performance:
Example:
public static int binarySearch(int[] array, int value)
{
int first; last, middle, position;
boolean found = false;
= 0;
first = array.length - 1;
last = -1;
position while (!found && first <= last) {
= (first + last) / 2;
middle if (array[middle] == value) {
= true;
found = middle;
position }
else if (array[middle] > value)
= middle - 1;
last else
= middle + 1;
first }
return position;
}
Header:
public static void main(String[] args)
Important: Remember to parse strings into numeric values if you want to use numeric values!
Example: Command-line arguments
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!
- Note how the arguments are tokenized and delimited by the whitespaces.
vararg: Special type parameter.
Printf
actually uses Object...
vararg.public static int sum (int... numbers) {
int sum = 0;
for (int x : numbers)
+= x;
sum 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<>();
.add("Bob");
nameList.add("Alice");
nameList.add(0, "Bingus");
nameList.remove(2);
nameList.set(1, "Dingus");
nameListSystem.out.println("nameList: " + nameList);
}
}
$ javac list.java && java list
nameList: [Bingus, Dingus]