Chapter 7: Single-Dimensional Arrays

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

___are the foundational random access data structure.

Arrays

The ___ method can be used to return a string representation for the list.

Arrays.toString(list)

What are the steps of creating an array?

Declare Instantiate Initialize

___ variables that are instantiated at run-time with the new keyword

Dynamic

After an array is created, an indexed variable cannot be used in the same way as a regular variable. True or false?

False

For the binarySearch method to work, the array does not have to be pre-sorted in increasing order. True or false?

False

anonymous array

An array created without an explicit reference.

___object are created without a name, often in method parameter lists. They are used one time and then discarded, so there's no reason to give them a name.

Anonymous

Array

a data structure that represents a collection of the same types of data

Suppose int i = 5, which of the following can be used as an index for array double[ ] t = new double[100]? a. i b. (int)(Math.random() * 100)) c. i + 10 d. i + 6.5

a,b, and c The array t has 100 elements and its index is an integer from 0 to 99.

For a parameter of an array type, the value of the parameter contains a reference to an array; this reference is passed to the method. Any changes to the array that occur inside the method body will ...

affect the original array that was passed as the argument

Once an array is created, its size ___.

is fixed

A variable number of arguments of the same type can be...

passed to a method and treated as an array

If an array is ___, binary search is more efficient than linear search for finding an element in an array.

sorted

sort/parallelSort method

sorts a whole array or a partial array

sort(numbers)

sorts the whole array numbers

When you pass an array to a method, the method receives___.

the reference of the array

When you return an array from a method, the method returns___.

the reference of the array

When passing an array to a method...

the reference of the array is passed to the method

Arrays.toString(list) method

used to return a string representation for the list

The two distinguishing features of arrays are:

•Identical data types •Stored end-to-end (contiguously)

For a parameter of a primitive type value, the actual value is passed. Changing the value of the local parameter inside the method ...

does not affect the value of the variable outside the method

All arrays in Java are ___, meaning that memory is allocated to the arrays at run-time rather than compile-time.

dynamic

selection sort

finds the smallest number in the list and places it first then finds the smallest number remaining and places it second, and so on until the list contains only a single number

If a variable does not contain a reference to an array, the value of the variable is ___.

null

What is the correct header of the main method?

public static void main(String[] args) public static void main(String args[]) public static void main(String[] x) public static void main(String x[])

base address

the address value of the starting point of the array

When a method returns an array...

the reference of the array is returned

The two consequences of array features are:

•Random Access (access time is not dependent on position) •Fixed Size (once you instantiate an array, you can't make it bigger)

garbage collection

Releases memory that was used for a variable's value once the variable is no longer to be used by a program.

The ___ method copies the sourceArray to the targetArray.

System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);

The reverse method returns a new array that is the reversal of the source. True or false?

True

Array Initializer syntax:

double[] myList = {1.9, 2.9, 3.4, 3.5};

Indexed Variables

the number in the brackets, []

Assume int[] t = {1, 2, 3, 4}. What is t.length?

4

Random Shuffling

Use the random() Method to Shuffle an Array in Java

Integer.parseInt(args[0])

converts a digital string into an integer

heap

area in the memory where the JVM stores the objects of an array

How can you get the word "abc" in the main method from the following call? java Test "+" 3 "abc" 2

args[2]

arraycopy Utility

array copy(sourceArray, src_pos, targetArray, tar_pos, length); Example: System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);

Declaring an array

datatype [ ] arrayRefVar;

The ___ is not used in the array-initializer syntax.

new operator

Binary Search

A search algorithm that starts at the middle of a sorted set of numbers and removes half of the data; this process repeats until the desired value is found or all elements have been eliminated.

How do you declare, create, initialize Using the Shorthand Notation?

declare, create, and initialize the array all in one statement

How can the address of the desired element be computed?

(base address + size * index)

If a key is not in the list, the binarySearch method returns___.

-(insertion point + 1)

Assume int[] scores = {1, 20, 30, 40, 50}, what value does java.util.Arrays.binarySearch(scores, 3) return?

-2 because the binarySearch method returns the index of the search key if it is contained in the list. Otherwise, it returns - insertionPoint - 1.

In the following code, what is the output for list2? public class Test { public static void main(String[] args) { int[] list1 = {1, 2, 3}; int[] list2 = {1, 2, 3}; list2 = list1; list1[0] = 0; list1[1] = 1; list2[2] = 2; for (int i = 0; i < list2.length; i++) System.out.print(list2[i] + " "); } }

0 1 2 list2 = list1 makes list2 point to the same array as list1

In the following code, what is the output for list1? public class Test { public static void main(String[] args) { int[] list1 = {1, 2, 3}; int[] list2 = {1, 2, 3}; list2 = list1; list1[0] = 0; list1[1] = 1; list2[2] = 2; for (int i = 0; i < list1.length; i++) System.out.print(list1[i] + " "); } }

0 1 2 because list2 = list1 makes list2 point to the same array as list1.

When an array is created, its elements are assigned the default value of...

0 for the numeric primitive data types '\u0000' for char types false for Boolean types

When an array is created, its elements are assigned the default value of:

0 for the numeric primitive data types, '\u0000' for char types, and false for boolean types

What is the output of the following code? double[] myList = {1, 5, 5, 5, 5, 1}; double max = myList[0]; int indexOfMax = 0; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) { max = myList[i]; indexOfMax = i; } } System.out.println(indexOfMax);

1 The code displays the index of the first max value in the array.

What is output of the following code: public class Test { public static void main(String[] args) { int list[] = {1, 2, 3, 4, 5, 6}; for (int i = 1; i < list.length; i++) list[i] = list[i - 1]; for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); } }

1 1 1 1 1 1 The first element is copied to the second, the second is then copied to the third, and so on.

What is the output of the following code? int[] myList = {1, 2, 3, 4, 5, 6}; for (int i = myList.length - 2; i >= 0; i--) { myList[i + 1] = myList[i]; } for (int e: myList) System.out.print(e + " ");

1 1 2 3 4 5 See Shifting elements in Item #8

What is the output of the following code? double[ ] myList = {1, 5, 5, 5, 5, 1}; double max = myList[0]; int indexOfMax = 0; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) { max = myList[i]; indexOfMax = i; } } System.out.println(indexOfMax);

1, the code displays the index of the first max value in the array.

Examples of processing an array

1. Initializing arrays with input values 2. Initializing arrays with random values 3. Printing arrays 4. Summing all elements 5. Finding the largest element 6. Finding the smallest index of the largest element 7. Random shuffling 8. Shifting elements

Ways to copy an array

1. Use a loop to copy individual elements one by one. 2. Use static arrayCopy method in the System class. 3. Use the clone method to copy arrays.

What is output of the following code: public class Test { public static void main(String[] args) { int[] x = {120, 200, 016}; for (int i = 0; i < x.length; i++) System.out.print(x[i] + " "); } }

120 200 14 016 is an octal number. The prefix 0 indicates that a number is in octal.

Assume int[] scores = {1, 20, 30, 40, 50}, what value does java.util.Arrays.binarySearch(scores, 30) return?

2

If you declare an array double[] list = {3.4, 2.0, 3.5, 5.5}, list[1] is ___ .

2.0

If you declare an array double[] list = {3.4, 2.0, 3.5, 5.5}, list[1] is ___.

2.0

If you declare an array double[] list = new double[5], the highest index in array list is ___.

4

How many elements are in array double[] list = new double[5]?

5

Vectors

Arrays with some built-in memory management, which allows features such as re-sizing the array. They are safer than arrays in some ways but much slower.

Between linear and binary, which search method is more efficient?

Binary but the array must be presorted

The ___object is anonymous; the only reason we need it is to instantiate the Scanner object, so it doesn't get a name.

File Scanner f = new Scanner(new File(fileName));

Arrays.parallelSort(list) syntax

For sorting data in ascending order: public static void parallelSort(Object obj[]) For sorting data in specified range in ascending order: public static void parallelSort(Object obj[], int from, int to)

for each loop syntax

In general, the syntax is for (elementType value: arrayRefVar) { // Process the value } You still have to use an index variable if you wish to traverse the array in a different order or change the elements in the array.

Processing Command-Line Parameters

In the main method, get the arguments from args[0], args[1], ..., args[n], which corresponds to arg0, arg1, ..., argn in the command line.

main()

It is a default signature which is predefined in the JVM. It is called by JVM to execute a program line by line and end the execution after completion of this method. We can also overload the main() method.

Arrays.sort Method

It takes three parameters as can be perceived from the syntax which is as follows: The array to be sorted The index of the first element, inclusive, to be sorted (Referred to as from_index) The index of the last element, exclusive, to be sorted (Referred to as last_index)

When invoking a method with a variable number of arguments...

Java creates an array and passes the arguments to it

When the main method is invoked...

Java interpreter creates an array to hold the command-line arguments and pass the array reference to args

Shuffling

Randomly reorder the elements in an array by using swap.

binarySearch method

Returns the index of the element in the list that matches the search key if it is contained in the list. Otherwise, it returns -insertion point - 1. The insertion point is the point at which the key would be inserted into the list.

___finds the smallest number in the list and places it first. It then finds the smallest number remaining and places it second, and so on until the list contains only a single number.

Selection Sort

What would be the outcome of the following code: double[] myList; myList = {1.9, 2.9, 3.4, 3.5};

Splitting it would cause a syntax error. Using the shorthand notation, you have to declare, create, and initialize the array all in one statement.

Linear Search

Start from the leftmost element of arr[ ] and one by one compare x with each element of arr[ ] If x matches with an element, return the index. If x doesn't match with any of elements, return -1.

___variables are instantiated at compile time.

Static

Analyze the following code: int[] list = new int[5]; list = new int[6];

The code can compile and run fine. The second line assigns a new array to list.

Suppose a method p has the following heading: public static int[] p() What return statement may be used in p()?

The correct syntax to create an array is new int[]{1, 2, 3}.

String args[]

The main() method also accepts some data from the user. It accepts a group of strings, which is called a string array. It is used to hold the command line arguments in the form of string values.

What would be the result of attempting to compile and run the following code? public class Test { public static void main(String[] args) { double[] x = new double[]{1, 2, 3}; System.out.println("Value is " + x[1]); } }

The program compiles and runs fine and the output "Value is 2.0" is printed.

Analyze the following code: public class Test { public static void main(String[] args) { int[] x = {1, 2, 3, 4}; int[] y = x; x = new int[2]; for (int i = 0; i < x.length; i++) System.out.print(x[i] + " "); } }

The program displays 0 0 because y is {1, 2, 3, 4} and x is {0, 0}

Analyze the following code: public class Test { public static void main(String[] args) { int[] x = {1, 2, 3, 4}; int[] y = x; x = new int[2]; for (int i = 0; i < y.length; i++) System.out.print(y[i] + " "); } }

The program displays 1 2 3 4 because y is {1, 2, 3, 4} and x is {0, 0}

Analyze the following code: public class Test { public static void main(String[] args) { double[] x = {2.5, 3, 4}; for (double value: x) System.out.print(value + " "); } }

The program displays 2.5 3.0 4.0

Analyze the following code: public class Test { public static void main(String[] args) { int[] a = new int[4]; a[1] = 1; a = new int[2]; System.out.println("a[1] is " + a[1]); } }

The program displays a[1] is 0. After executing the statement a = new int[2], a refers to int[2]. The default value for a[0] and a[1] is 0.

Analyze the following code: public class Test { public static void main(String[] args) { final int[] x = {1, 2, 3, 4}; int[] y = x; x = new int[2]; for (int i = 0; i < y.length; i++) System.out.print(y[i] + " "); } }

The program has a compile error on the statement x = new int[2], because x is final and cannot be changed.

Analyze the following code: public class Test { public static void main(String[] args) { int[] x = new int[5]; int i; for (i = 0; i < x.length; i++) x[i] = i; System.out.println(x[i]); } }

The program has a runtime error because the last statement in the main method causes ArrayIndexOutOfBoundsException.

Analyze the following code. public class Test { public static void main(String[] args) { int[] x = new int[3]; System.out.println("x[0] is " + x[0]); } }

The program runs fine and displays x[0] is 0.

Analyze the following code. public class Test { public static void main(String[] args) { int[] x = new int[3]; System.out.println("x[0] is " + x[0]); } }

The program runs fine and displays x[0] is 0.

What happens if the main() method is written without String args[]?

The program will compile, but not run, because JVM will not recognize the main() method.

Why are for loops often used to process arrays?

The size of the array is known so it is only natural to use a for loop and all of the elements in an array are of the same type.

For an array of size s the elements are numbered 0 to s - 1. True or false?

True

Java treats a variable-length parameter as an array. True or false?

True

Once an array is created, its size is fixed; cannot be changed. True or false?

True

Pass By Value

Used e to pass arguments to a method

Arrays.binarySearch Method

Used for searching a key in an array of int, double, char, short, long, and float in the java.util.Arrays class.

for-each loop

Used to display items in an array without having to use an index variable.

Arrays.parallelSort(list)

Uses concept of MultiThreading which makes the sorting faster as compared to normal sorting method.

command-line argument

any information that directly follows the program's name on the command line when it is executed

Assume int[] scores = {1, 20, 30, 40, 50}, what is the output of System.out.println(java.util.Arrays.toString(scores))?

[1, 20, 30, 40, 50]

What is the representation of the third element in an array called a?

a[2]

How can arrays be copied?

array1 = array2; or arraycopy Utility or use a for loop

To assign a values to the elements, use the syntax:

arrayRedVar[index] = value;

Creating Arrays

arrayRefVar = new datatype[arraySize];

Each element in the array is represented using the following syntax, known as an indexed variable:

arrayRefVar[index];

arrayCopy Utility

arraycopy(sourceArray, src_pos, targetArray, tar_pos, length); Example: System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);

Which of the following statements are valid? a. int i = new int(30); b. double d[] = new double[30]; c. int[] i = {3, 4, 3, 2}; d. char[] c = new char(); e. char[] c = new char[4]{'a', 'b', 'c', 'd'};

b and c

For an array of ___ type, it can be printed using one print statement such as in this example: char [ ] city = {'D', 'a', 'l' , 'l', 'a', 's'}; System.out.println(city);

char

How can you initialize an array of two characters to 'a' and 'b'?

char[] charArray = {'a', 'b'}; or char[] charArray = new char[2]; charArray[0] = 'a'; charArray[1] = 'b';

The JVM stores the array in an area of memory, called ___ , which is used for dynamic memory allocation where blocks of memory are allocated and freed in an arbitrary order.

heap

The JVM stores the array in an area of memory, called ___, which is used for dynamic memory allocation where blocks of memory are allocated and freed in an arbitrary order.

heap

Data Structures

how we organize data for effective storage and retrieval

The array elements are accessed through the ___.

index

What is the correct term for numbers[99]?

indexed variable

Copying Arrays Using a loop:

int[] sourceArray = {2, 3, 1, 5, 10}; int[] targetArray = new int[sourceArray.length]; for (int i = 0; i < sourceArrays.length; i++) targetArray[i] = sourceArray[i];

0-based

it starts from 0 to arrayRefVar.length-1

The ___ class contains various static methods for sorting and searching arrays, comparing arrays, filling array elements, and returning a string representation of the array.

java.util.Arrays

The ___ method sorts the array scores of the double[] type.

java.util.Arrays.sort(scores)

The ___ can receive string arguments from the command line.

main method


Kaugnay na mga set ng pag-aaral

AP Euro Vocabulary Industrial Revolution

View Set

Foundations Unit Test Two (Ch. 5-8)

View Set

Unit Three Exam - Purchasing & Receiving

View Set

Physiological Psychology Final Exam

View Set

Algebra I - Unit 1: Foundations of Algebra Test

View Set