Arrays & Array Lists Flashcards

1
Q

Array

A

A collection of values of the same type stored in contiguous memory locations, each of which can be accessed by an integer index.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you declare an array?

A

As with other objects, you have to use the new keyword to create an array and assign its memory address to a variable. Simply declaring an array reference variable does not create an array. You must take both steps:

double [] values = new double [10];

OR

int [] numbers;

numbers = new int[6];

However, when you declare an array you can also specify the initial values, in which case you don’t use the new keyword. The compiler will determine the length of the array for you by counting the inputs:

double [] moreValues = {32, 54, 78, 16, 20};

*Note, if you do not initialize an array with values then each values is 0 by default.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Size declarator

A

The number inside the brackets of an array initialization that specifies the size or length of the array. This is important because once the amount of elements that an array can hold is set it cannot be changed. While an array’s size declarator must be a non-negative integer, it can be expressed as a literal value or a variable. It is common practice to use a final variable as a size declarator:

final int NUM_ELEMENTS = 6;

int[] numbers = new int[NUM_ELEMENTS];

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Subscript

A

Each element in an array is assigned a number known as a subscript. It is used as an index to pinpoint a specific element. The first element is subscript 0, the second element is subscript 1, and so forth.

*Note, you can use variables and calculations in subscripts. For example:

public boolean firstLast6(int[] nums)
{
if (nums[0] == 6 || nums[nums.length-1] == 6)
{
return true;
}
return false;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you access elements of an array?

A

You can use the subscript to access and use elements as individual variables. This is done with the notation array[i].

For example, to assign a value to specific element:

values[4] = 35;

To display a specific value:

System.out.println(values[4]);

To compare elements:

if (cost[20] < cost[17] )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do you print the contents of an array?

A

Depending on the desired format, you can either write a loop or call the Array class’s toString( ) method. For example:

String[] friends = {“Sally”, “Anna”, “Maureen”};

// Print with loop

for (String friend : friends)

{

System.out.println(friend);

}

// You could also write this loop as follows:

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

{

System.out.println( friends.get( i ));

}

// Using the toString( ) method
System.out.println(Arrays.toString(friends));

* Note, the toString( ) method will return the results in the following format: [Sally, Anna, Maureen]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Bounds error

A

Trying to access an array element that is outside the legal range, which is the most common error when working with arrays. For example, in the following array, the valid subscripts are 0 to 9. Java will not allow a statement to use a subscript that is less than 0 or greater than 9 with this array:

int[] values = new int[10];

However, it is common to make an “off by one error” when accessing array elements and in this case, try to access element 10, which doesn’t exist, for example. Be careful because bounds checking occurs at runtime! The compiler will not display an error. This means it will cause your program to terminate.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Asymmetric bounds

A

Bounds that include the starting index but not the ending index.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How can you find the number of elements in an array?

A

Use the expression array.length

* Note, there are no parentheses!

You can also use this expression to ensure that you only access elements within legal bounds:

if (0 <= i && i < values.length - 1)

{

// your code here

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Partially filled array

A

An array that is not filled to capacity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Companion variable

A

A companion variable keeps track of how many elements are used in a partially filled array. For example, in the following code that collects inputs and stores it in an array, currentSize is a companion variable:

int currentSize = 0;

Scanner in = new Scanner(System.in); while(in.hasNextDouble())

{

if(currentSize < values.length)

{

values[currentSize] = in.nextDouble();

currentSize++;

}

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Unfilled array

A

Allocating an array variable without actually filling it is another common error that’s made when working with arrays. For example, the following statement creates an array variable but does not fill it with any objects:

BankAccount[] accounts = new BankAccount[10];

To fill it with accounts you also need to do something akin to the following:

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

{

accounts[i] = new BankAccount();

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Parallel arrays

A

Arrays of the same length, in which corresponding elements are logically related, such as: int[] accountNumber; double[] balance; This is poor design and should be converted into a single array of objects that hold the related information. In this case, the parallel arrays should be changed to a single BankAccount array: BankAccount[] accounts;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Enhanced for loop

A

A short cut to visit, or traverse, all elements in a set such as an array. The following example sums all elements in an array: double[] values = { 6, 8, 16, 27…..} double total = 0; for (double element : values) { total = total + element; } However, it has some significant limitations. Chiefly, it does not allow you to modify values. For example, the following loop does not fill each element in the array with 0 (although this can be done with a basic for loop): for (double element : values) { element = 0; // error! }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Common array algorithms: Filling an array with values

A

The following loop fills an array with squares (0, 1, 4, 9, 16…..): for (int i = 0; i < values.length; i++)

{

values[i] = i * i;

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Common array algorithms: Sum and average value

A

To compute a sum:

// initialize an accumulator

double sum = 0;

for (double element : values)

{

sum += element;

}

To compute the average just add a counter to the loop above and then divide the total by the counter.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Common array algorithms: Finding the maximum value

A

// initialize value with first array element

double max = values[0];

for (int i = 1; i < values.length; i++)

{

if (values[i] > max)

{

max = values[i];

}

}

* Note that the loop starts at 1 since we set the first element to the maximum value seen so far. Thus we cannot use an enhanced for loop here.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Common array algorithms: Finding the minimum value

A

// initialize value with first array element

double min = values[0];

for (int i = 1; i < values.length; i++)

{

if (values[i] < min)

{

min = values[i];

}

}

* Note that the loop starts at 1 since we set the first element to the minimum value seen so far. Thus we cannot use an enhanced for loop here.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Common array algorithms: Linear search

A

Also known as sequential search, this algorithm uses a loop to sequentially search through an array, starting with the first element. It compares each element with the target value and stops when the value is found or the end of the array is reached. For example, the following loop searches for the first element in an array that is equal to 100:

int searchedValue = 100;

int position = 0;

boolean found = false;

while (position < values.length && !found)

{

if (values[position] == searchedValue)

{

found = true;

}

else

{

position++;

}

if (found)

{

System.out.println(“Found at position “ position);

}

else

{

System.out.println(“Not found”);

}

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Common array algorithms: Separating elements for display

A

When you display the elements of an array you usually want to separate them, often with commas or pipe delimiters: 32 | 54 | 67 | 12 | 3 Note that there is one fewer separator than numbers. Therefore you print the separator before each array element except the first one:

for (int i = 0; i < values.length; i++)

{

if (i > 0)

{

System.out.print(“ | “);

}

System.out.print(values[i]);

}

For comma separators, you can use the Arrays.toString method:

Arrays.toString(values)

This returns: [32, 54, 67, 12, 3]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Common array algorithms: Removing an element

A

How you do this depends on whether or not the array is sorted. If it’s not, then you simply replace the value you want to remove with the last value and decrement the companion variable to keep track of the size of the array:

values[position] = values[currentSize - 1];

currentSize—;

Otherwise, if the array is sorted, then you must move all elements after the element you’re removing to a lower index and then decrement the companion variable:

for (int i = position + 1; i < currentSize; i++)

{

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

currentSize—;

}

* Note you don’t actually remove a value in either case. You overwrite the value you want to remove with another.

22
Q

Common array algorithms: Inserting an element

A

Similar to removing an element, how you do this depends on if the array is sorted or not. If it’s not, then you can simply insert the new element at the end and increment the companion variable:

if (currentSize < values.length)

{

values[currentSize + 1] = newElement;

currentSize++;

}

If orders matters, then you move all elements after the insertion location to a higher index and then insert the new element (in this the target insert location is index 3)

if (currentSize < values.length)

{

for (int i = currentSize; i > position; i–)
{

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

}

values[position] = newElement;

}

23
Q

Common array algorithms: Swapping elements

A

Use a temp variable to save the first element and then replace it with the second:
double temp = values[i];

values[i] = values[j];

values[j] = temp;

24
Q

Common array algorithms: Reversing elements

A

public int[] reverse3(int[] nums)
{
int[] reverse = new int[nums.length];
int j = nums.length;
for (int i = 0; i < nums.length; i++)
{
reverse[j - 1] = nums[i];
j = j - 1;
}
return reverse;
}

25
Q

Common array algorithms: Copying arrays

A

Array variables do not hold array elements; they only hold array references. Therefore, if you copy the reference, you only get another reference to the same array.

If you want to make a true copy of an array then you call the Arrays.copyOf method. The call Arrays.copyOf(values, n) allocates an array of length n, copies the first n elements of values into it, and returns the new array. Just be sure to import the Arrays class by importing the java.util package!

* Note that a common use of this method is to grow an array that has run out of space. For example, the following statements double the size of an array:
double[] newValues = Arrays.copyOf(values, 2 * values.length);
values = newValues;

26
Q

Common array algorithms: Reading input

A

It’s simple to read user input into an array if you know the size in advance:
double[] inputs = new double[NUMBER_OF_INPUTS];

for(i = o; i < inputs.length; i++)

{

inputs[i] = in.nextDouble();

}
However if you need to read a stream of user input, then:
double[] inputs = new double[INITIAL_SIZE};

int currentSize = 0;

while(in.hasNextDouble())
{
 // Grow the array if it's been filled
 if (currentSize \>= inputs.length)
 {
 inputs = Arrays.copyOf(inputs, 2 \* inputs.length);
 }
 inputs{currentSize] = in.nextDouble();

currentSize++;
}

// Discard any unused elements
inputs = Arrays.copyOf(inputs, currentSize);
27
Q

Common array algorithms: Sorting elements

A

To sort an array values, call:
Arrays.sort(values);

If the array is partially filled, call:
Arrays.sort(values, 0, currentSize);

28
Q

Null pointer exception

A

A NullPointerException is thrown when a program attempts to use an object reference that has the null value. This is a runtime error that you need to careful to avoid when working with arrays, since it’s possible that not every element is populated. Therefore, you need to check for null values before processing array elements with an algorithm, such as summing values or calculating the average.

For example, in the following loop that returns the color of every car parked in a garage, there is a null value check performed first, since every spot in the garage may not be filled with a car:
for (i = 0; i < parkingSpaces.length; i++)
{
if(parkingSpaces[i] != null)
{
return carColor;
}
}

29
Q

What are the key steps to working with an array effectively?

A
  1. Decompose your task into steps. This may include:
    • Reading data into an array
    • Processing the data in one or more steps
    • Displaying the results
  2. Determine which algorithm(s) you need. Most problems involving an array can be solved with one or more of the common array algorithms already reviewed. Therefore it’s important to understand these so they can be combined or modified to solve more specific problems.
  3. Use classes and methods to structure the program. For example, if we were writing a program to calculate students’ final score for a class by calculating the average of multiple grades, then we may break this down as follows:
    • Student class holds an array of test scores
    • ScoreAnalyzer class reads user input of test scores and calculates the final score
  4. Assemble and test the program. At this point it’s important to think through exceptional situations. For example, what happens if there’s an empty array? What if there’s only a single element in the array? Make sure your program can handle all such boundary cases so there are no unintended results or crashes.
30
Q

Two-dimensional (2D) array

A

A two-dimensional array is an array of arrays. However, it can be thought of as a set, tabular arrangement, of data in which an element is specified by a row and a column index. As a result, it is also, known as a matrix.

A 2D array is a good option when you need to work with multiple sets of data such as scores for multiple students in a class. That is, instead of creating separate arrays for each student’s scores, you can create a 2D array of test scores for the whole class where each row represents a student and each column represents a score.

31
Q

How do you declare a two-dimensional array?

A

You declare a two-dimensional array by supplying the number of rows and columns. For example, int[7][3] is an array with 7 rows and 3 columns. Similar to one-dimensional arrays, the size declarator can be expressed as a variable, such as:
final int COUNTRIES = 7;

final int MEDALS = 3;

int[][] counts = new int[COUNTRIES][MEDALS];

Alternatively, you can also declare and initialize the two-dimensional array at the same time:
int[][] counts = { 1, 0, 1 },

{ 0, 1, 0 },
etc……..

32
Q

How do you access the elements of a two-dimensional array?

A

Individual elements are accessed by using two index values, array[i][j], where [i] represents the row index and [j] represents the column index.

For example, to assign a value to specific element:

scores[2][1] = 95;

To display a specific value:

System.out.println(scores[2][1]);

To access all elements of a two-dimensional array, you use nested loops. For example, the following code prompts the user to enter a score and stores them in each element of the 2D array:

final int ROWS = 3;

final int COLS = 4;

double[][] scores = new double[ROWS][COLS];

for (int row = 0; row < ROWS; row++)

{
for (int col = 0; col < COLS; col++)
{
System.out.print(“Enter a score: “);
scores[row][col] = keyboard.nextDouble();
}
}

33
Q

Neighboring elements

A

A term used to describe adjacent elements in a two-dimensional array. When locating neighboring elements, you need to be careful to handle the boundary of the array correctly. For example, counts[0][1] has no neighbor on top.

34
Q

How do you display the number of rows in a 2D array?

A

A 2D array has multiple length fields. One holds the number of rows and then each row has a length field that holds the number of columns.

To get the number of rows, you simply call the length method with the array reference:
scores.length;

35
Q

How do you display the number of columns in each row of a 2D array?

A

A 2D array has multiple length fields. One holds the number of rows and then each row has a length field that holds the number of columns.

To get the number of columns in a row, you call the length method on a specific row using the subscript:
numbers[index].length;

36
Q

Common 2D array algorithms: Displaying all elements

A

int[][] numbers = { { 1, 2, 3, 4 },

{ 5, 6, 7, 8 },

{ 9, 10, 11, 12 } };

for (int row = 0; row < numbers.length; row++)
{
for (int col = 0; col < numbers[row].length; col++)
{
System.out.println(numbers[row][col]);
}
}

37
Q

Common 2D array algorithms: Summing all elements

A

int sum = 0;

for (int row = 0; row < numbers.length; row++)

{

for (int col = 0; col < numbers[row].length; col++)

{

sum += numbers[row][col];

}

}

System.out.println(“The total of all elements in the array is: “ + sum);

38
Q

Common 2D array algorithms: Summing a row

A

// Sum all elements in row two the 2D array

int rowTwoSum = 0;

for (int col = 0; col < numbers[2].length; col++)

{

rowTwoSum += numbers[2][col];
}

39
Q

Common 2D array algorithms: Summing a column

A

int colTwoSum = 0;

for (int row = 0; row < numbers.length; row++)

{

colTwoSum += numbers[row][2];

}

System.out.println(“The total of all elements in column two is: “ + colTwoSum);

40
Q

Ragged array

A

An 2D array with rows of different lengths

41
Q

Array list

A

A Java class that implements a dynamically-growable array of objects. It offers two main advantages over an array:

  • It automatically grows and shrinks as items are added or removed
  • The ArrayList class supplies methods for common tasks, such as inserting and removing elements
42
Q

How do you declare an ArrayList?

A

ArrayList<string> friends = new ArrayList<string>();<br></br>Where the information supplied in the angled brackets, &lt; &gt;, is the type parameter. While it is a String in this case, an ArrayList can hold any type of object. </string></string>

43
Q

How do you find the size or length of an ArrayList?

A

Contrary to Strings, which use the length() method and arrays, which use the length method, the size() method is used for ArrayLists:

friends.size();

44
Q

What are the most commonly used methods in the java.util.ArrayList package to work with array lists?

A
  • add(value) / add(index, value) - If you use the former then the value is added at the end of the ArrayList. If you use the latter then the value is inserting into the ArrayList at a specific position and moves all elements with that index or larger by 1.
  • get(index) - Retrieves an element at a specified position
  • remove(index) - Removes an element at the specified position, moving all elements after the removed element down by 1 position and reducing the size of the ArrayList by 1.
  • set(index, value) - Contrary to the add method, this overwrites, or replaces, existing values.
45
Q

What is the default capacity of an ArrayList?

A

10 items. However, you can specify a different starting capacity if you desire by passing an int argument to the ArrayList constructor:
ArrayList<string> list = new ArrayList<string>(100);</string></string>

46
Q

How do you print the contents of an ArrayList?

A

You can simply pass the reference to the ArrayList to the println() method. For example:
System.out.println(friends);

This will display the elements in the ArrayList in the following manner:
[James, Catherine, Bill]

It does so by calling the ArrayList class’s toString method that returns a string representation of all elements stored in the ArrayList.

47
Q

How do you copy an ArrayList?

A

As with arrays, ArrayList variables hold references. Therefore, to make a copy of an ArrayList, construct the copy and pass the original list into the constructor:
ArrayList<string> newFriends = ArrayList<string><strong>(friends);</strong></string></string>

48
Q

Wrapper Class

A

A wrapper class is class that is “wrapped around” a primitive data type and allows you to create objects instead of variables. In Java, you can use ArrayLists with primitive data types, so you must use one of the following wrapper classes instead:
Byte
Boolean
Character
Double
Float
Integer
Long
Short

49
Q

Autoboxing

A

Java’s process of automatically converting a primitive type value into a wrapper type object. This is rarely used but is convenient to leverage when you want to perform an operation on a primitive variable, but the operation can only be used with an object. For example, an ArrayList cannot hold primitive values; it’s intended for objects only. Therefore if you want to store integers in an ArrayList, you can use the wrapper class, Integer. Autoboxing will performed automatically whenever an integer is added so you don’t need to create an object first.

50
Q

Unboxing

A

The opposite of autoboxing. It is the process of converting a wrapper class object to a primitive type. Continuing with the ArrayList of Integers example, unboxing will be automatically performed if an integer is removed from the list. That is it can stored as a primitive data type int automatically.