JAVA ARRAYS

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Write a piece of code to initial an array called g that's 2x3x2 to even numbers starting with zero. n=0;

for (int d=0; d< 2; d++) for (int c=0; c< 3; c++) for (int r=0; r<2; r++) g[r][c][d] = n; n = n + 2;

How to fill or search a 2D array.

for (int i = 0; i < ROWS; i++) for (int j = 0; j < COLUMNS; j++) board[i][j] = " ";

How to fill or search a 2D array.

for (int i = 0; i < ROWS; i++) for (int j = 0; j < COLUMNS; j++) board[i][j] = " ";

Write a piece of code to initialize the five elements of a one-d array to the int value of 10.

for (int i=0; i<5; i++) sample[i] = 10;

for each loop syntax

for (variable : collection) {statement}

Even though will typically use one step to declare an array, the creation of an array is a two step process, what are the two steps?

int sample[]; sample = new int[10]

cup is an array of doubles. It has more than 50 values, like 1, 2.5, 4.2 cc. Set the last element to 23 cc.

int size=cup.length; cup[size-1]=23;

A 3-d array is useful for? example?

spreadsheet + tabs = 3d simulations moderating in science/engineering. double[][][] data = new double[4][1000][100]; 4d is dealing with time.

see slide 9 for a basic array example and slide 10 for a diagram showing what happens.

ssh

student is an array. It has more than 50 items, like "Mark", "Abe", "Jane". Set the 2nd item to "Gary".

student[1]="Gary";

student is an array. It has more than 50 items, like "Mark", "Abe", "Jane". Set the 4th item to "Gary".

student[3]="Gary";

Alternate Array Declaration Notation

style 1: int[ ] numbers; style 2: int numbers[ ]; int numbers[ ], codes[ ], scores[ ];

Each element of an array is accessed by a number known as a(n)...

subscript

Using an array with more than ___ dimensions is ____ in an object-oriented system.

two, rare

printing an array backwards:

use a for loop: for (int index = scores.length() -1; index >= 0; index--; { System.out.println(scores[index]); }

Each ___ (or ____) in an array has a numeric ___.

value, element, index

Variable-Length Argument Lists

variable-length argument lists, which makes it possible to write a method that takes a variable number of arguments

A Java method can be defined to accept a ___ number of ___ .

varying, parameters

the java compiler

what counts the number of elements inside the brackets and uses that as the size of the array?

array index out of bounds exception -1

what error will you get is you try to access an element less than zero?

java.util.Arrays

what holds all the java array methods

flag variable and a for loop

what two things do you need to compare two arrays?

no

when specifically instantiating an array, is the new keyword used?

nothing

when specifically instantiating an array, what goes inside of the []?

Array bounds checking happens...

when the program runs

use the for each loop in an array/arraylist when you want to do what?

when you want to do a calculation. When you want to change the values of the array use a for loop.

Capacity

which is the number of items it can store without having to increase its size. - When an ArrayList object is first created, using the no-arg constructor, it has an initial capacity of 10 items. -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);

Suppose data is the string "BrokenBroken" What is the value of x in the expression x = data.lastIndexOf("on") ?

x = -1

Suppose data is the string "BrokenBroken" What is the value of x in the expression x = data.lastIndexOf("en") ?

x = 10

Suppose data is the string "BrokenBroken" What is the value of x in the expression x = data.indexOf("en"); ?

x = 4

If data = "Z", what is the value of x in the expression x = data.compareTo("B") ?

x = some positive number

Referring to #21, if x = bus.length, y = bus[0].length, and z = bus[1].length, what are the values for x , y, and z?

x =7 y = 4 z = 2

int myArray[] = {9, 3, 7, 2, 1, 8}; for(int qq=0; qq<myArray.length; qq++) { ....if(myArray[qq]<5) ....{ ........break; ....} ....System.out.print(myArray[qq] + " "); }

9

int myArray[] = {9, 3, 7, 2, 1, 8}; for(int qq=0; qq<myArray.length; qq++) { ....if(myArray[qq]==1) ....{ ........break; ....} ....System.out.print(myArray[qq] + " "); }

9 3 7 2

int myArray[] = {9, 3, 7, 2, 1, 8}; for(int qq=0; qq<myArray.length; qq++) { ....if(myArray[qq]<5) ....{ ........continue; ....} ....System.out.print(myArray[qq] + " "); }

9 7 8

command-line argument

Data provided on the command line when program is executed. Java stores these in the String array passed into the main method.

String[ ] schoolDays = {"mo", "tu", "we", "th", "fi"};

Declare array named schoolDays. Elements are mo, tu, we, th, fr (in that order).

String[ ] wkEnd = {"sat", "sun"};

Declare array named wkEnd. Elements are sat and sun.

String ID[] = {"m94", "k34", "s72"};

Declare array of ID numbers. with elements: m94, k34, s72

String[] week = new String[7];

Declare array week. It has 7 elements with names of the days of the week.

double[] cup=new double[50];

Declare cup array. It has 50 elements like 2.0, 3.3, 4.0 cc.

double[] cup={2, 3.3, 4};

Declare cup array. It has elements 2.0, 3.3, 4.12 cc.

String[] mth=new String[12];

Declare mth array for the months of the year.

String[] snack={"gum", "chips"};

Declare snack array. It has elements "gum", "chips".

int[] x = {10, 20, 30,40 };

Declare x array to hold elements 10, 20, 30, 40.

What type of an array would you use to hold the hours you work each day for a part time job (assume you work diff numbers of hours each day)?

Irregular

Explain what a Bubble sort is and how does it word? How many loop do you need?

It compares values at two index locations and does a swap if necessary. It repeats this process over and over. You need two loops

shift()

Removes the first element of an array, and returns that element

pop()

Removes the last element of an array, and returns that element

String replace(char oldChar, char newChar)

Replaces all occurrences of oldChar in this String with newChar

String substring(int beginIndex, int endIndex)

Returns a substring from beginIndex to endIndex - 1. endIndex can be left blank

static String valueOf(int i)

Returns the String representation of the int (or any other primitive type) argument

char charAt(int index)

Returns the char at the specified index

int hashCode()

Returns the hash code of a String

Create an appropriate array to hold the names and phone numbers of 3 people.

String numbers[][] = { {"Tom", "555-3322"}, {"Sam", "555-8976"}. {"Cole", "596-2142"} };

Can a string have just one character? Show an example

String one = "A"; char one = 'A';

Declare array phoneNum. It has 2 elements: 949-234-5678 and 714-626-1234

String phoneNum[] = {"949-234-5678", "714-626-1234"};

List an easier way to construct a string

String statement = "Hello";

List a way to construct a string

String statement = new String("Hello");

Create a string with the characters, "Hello"

String str = "Helllo";

Declare array named week. Elements are mon tue wed thu fri sat sun (in that order).

String week[] = {"mon", "tue", "wed", "thu", "fri", "sat", "sun"};

Declare an array for the months of the year.

String[] months=new String[12];

snack is an array of 50 food names. Declare this array.

String[] snack=new String[50];

Declare snack array. It has elements "gum", "chips".

String[] snack={"gum", "chips"};

Declare array week. It has 7 elements.

String[] week = new String[7];

Syntax of System.arraycopy method.

System.arraycopy(from, fromStart, to, toStart, count);

boolean startsWith(String prefix)

Tests if this string starts with the specified prefix

Remove an Item from an ArrayList

The ArrayList class has a remove method that removes an item at a specific index. You pass the index as an argument to the method. nameList.remove(1);

ArrayList Class's toString method

The ArrayList class has a toString method that returns a string representing all of the items stored in an ArrayList objec

Inserting an item

The ArrayList class has an overloaded version of the add method that allows you to add an item at a specific index. nameList.add(1, "Mary");

Replacing an item

The ArrayList class's set method can be used to replace an item at a specific index with another item nameList.set(1, "Becky");

negative, 0, positive

The String compareTo method returns a ____ number if words[i] < largest, _ if they are equal (having the same value), and a_____ number if words[i] > largest

Finding the highest value

The code to find the highest value in the array is as follows: int highest = numbers[0]; for (int index = 1; index < numbers.length; index++) { if (numbers[index] > highest) highest = numbers[index]; }

resize

The copyOf method is often used to ______ an array

T/F - Java does not allow a statement to use a subscript that is outside the range of valid subscripts for an array.

True

T/F - The Java compiler does not display an error message when it processes a statement that uses an invalid subscript.

True

T/F - The subscript of the last element in a single-dimensional array is one less than the total number of elements in the array.

True

T/F - The values in an initialization list are stored in the array in the order that they appear in the list.

True

T/F - When an array is passed to a method, the method has access to the original array.

True

ArrayList

_______ <Students> pupil

Cars

________ [ ] xyz = new Cars[10]

Movie

________ [ ] xyz = new Movie[10]

for (int i = -2; i < 2; i++) what are the values of i?

-2 -1 0 1

toString()

Converts an array to a string, and returns the result

char[] toCharArray()

Converts this string to a character array

copyWithin()

Copies array elements within the array, to and from specified positions

filter()

Creates a new array with every element in an array that pass a test

map()

Creates a new array with the result of calling a function for each array element

T/F - A two-dimensional array has multiple length fields.

True

T/F - An ArrayList automatically expands in size to accommodate the items stored in it.

True

T/F - Both of the following declarations are legal and equivalent: int[] numbers; int numbers[];

True

primitive

the equals method works for arrays of _____ types

sort method

the given array using the QuickSort algorithm.

greater than or equal to 0

the index of an array must evaluate to an int that is ___ __ ___ __ ___ to work

area of memory

the instantiation of an array creates an ______ __ ______ that holds the elements of the array

Input and Output array contents

- You can read values from the keyboard and store them in an array element just as you can a regular variable. - You can also output the contents of an array element with print and println.

Arrays of Objects

- You may create arrays of objects that are instances of classes that you have written. - Objects in an array are accessed with subscripts, just like any other data type in an array.

Copying Arrays

- reference copy: both the array1 and array2 variables will reference the same array. - Only the address of the array object is copied, not the contents of the array object.

______ -___ arguments are stored in an array of ___ ___ and are passed to the __ method.

Command-line, String objects, main

Suppose data is the string "Broken" What is the value of part in the expression: part = data.substring(3,6); ? What type of variable is part?

"part" would be a string. In this case, the variable is "ken"

Array named days has days of the week. The elements are "mon", "tue", "wed", ... "sun". What is days[5]?

"sat"

Suppose the test against the the string is "supal," what value does y have? (Refer to #45)

"False," because all the characters must match for it to be true.

String concat(String s)

Concatenates the argument string to the end of this string and returns the new string

Suppose you have two arrays: num1 and num2. What does: num1 = num2 do?

(Option C) You are causing num1 to reference num2

____6.33

*CHALLENGE* What is the output? Use underscore ( _ ) to mimic space.

Selection sort

- A sorting algorithm is a technique for scanning through an array and rearranging its contents in some specific order. - The selection sort works like this: The smallest value in the array is located and moved to element 0. Then the next smallest value is located and moved to element 1. This process continues until all of the elements have been placed in their proper order

Two-Dimensional Arrays

- A two-dimensional array is an array of arrays. It can be thought of as having rows and columns - 2D arrays, can hold multiple sets of data - To declare a two-dimensional array, two sets of brackets and two size declarators are required: The first one is for the number of rows and the second one is for the number of columns double[][] scores = new double[3][4]; - To access one of the elements in a two-dimensional array, you must use both subscripts scores[2][1] = 95;

String Arrays

- An array of String objects may be created, but if the array is uninitialized, each String in the array must be created individually. String[] names = { "Bill", "Susan", "Steven", "Jean" }; - In order to use a String object, you must have a reference to the String object.

Calling String methods from an array element

- Because each element of a String array is a String object, you can use an element to call a String method - Because the array's length member is a field, you do not write a set of parentheses after its name. You do write the parentheses after the name of the String class's length method. for (int i = 0; i < names.length; i++) System.out.println(names[i].length());

Create and Use an ArrayList Object

- Create ArrayList<String> nameList = new ArrayList<String>();

Array Length

- Each array in Java has a public field named length. size = temperatures.length; for (int i = 0; i < temperatures.length; i++) System.out.println(temperatures[i]); - You cannot change the value of an array's length field.

three or more dimensions arrays

- It is possible to create arrays with multiple dimensions, to model data that occurs in multiple sets double[][][] seats = new double[3][5][8];

Command-line Arguments

- It is not required that the name of main's parameter array be args. You can name it anything you wish. It is a standard convention, however, for the name args to be used -

Binary search

- Its only requirement is that the values in the array must be sorted in ascending order. - Instead of testing the array's first element, this algorithm starts with the element in the middle.

Bounds Checking

- Java performs array bounds checking, which means that it does not allow a statement to use a subscript that is outside the range of valid subscripts for an array. - Bounds checking occurs at runtime. The Java compiler does not display an error message when it processes a statement that uses an invalid subscript. Instead, when the statement executes, the program throws an exception and immediately terminates.

Array Initialization

- Like regular variables, Java allows you to initialize an array's elements when you create the array. int[ ] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; - This statement declares the reference variable days, creates an array in memory, and stores initial values in the array. The series of values inside the braces and separated with commas is called an initialization list. - Note that you do not use the NEW key word when you use an initialization list - Java allows you to spread the initialization list across multiple lines.

Comparing Arrays

- To compare the contents of two arrays, you must compare the elements of the two arrays. // First determine whether the arrays are the same size. if (firstArray.length != secondArray.length) arraysEqual = false; // Next determine whether the elements contain the same data. while (arraysEqual && index < firstArray.length) { if (firstArray[index] != secondArray[index]) arraysEqual = false; index++; } if (arraysEqual) System.out.println("The arrays are equal."); else System.out.println("The arrays are not equal.");

Passing Arrays as Arguments to Methods

- To pass an array, you pass the value in the variable that references the array. showArray(numbers);

The Enhanced for Loop

- simplifies array processing. for (dataType elementVariable : array) statement; - The enhanced for loop is designed to iterate once for every element in an array

int[] x={ 3, 1, 4, 1, 5, 9, 2 }; int[] z={ 0, 7, 3, 1, 9, 4, 9 }; for(int j=1; j<=5; j++) { ....System.out.print( x[ j ] - z[ j ] + " " ); }

-6 1 0 -4 5

Write the contents of each element of the numbers array to a file

// Open the file. PrintWriter outputFile = new PrintWriter("Values.txt"); // Write the array elements to the file. for (int index = 0; index < numbers.length; index++) outputFile.println(numbers[index]); // Close the file. outputFile.close();

The first subscript in an array is always...

0

when an array is initialized, each list element has an initial value of ?

0

for (int m = 0; m <= 9; m = m + 2) what are the values of m?

0 2 4 6 8

What kind of number is the index value for an array?

0, or a positive integer

How many loops are necessary to find the largest number in an array?

1

int[] x={ 3, 7, 1, 9, 4, 0, 2 }; int[] y={ 0, 7, 3, 1, 9, 4, 9 }; for(int mm= _____; ______; _______) { . . . . System.out.print( x[ mm ] + y[ mm ] + " " ); } //This is tricky. Fill in the blank so that //it prints 14 10 4

1 j<=5 j=j+2

find the largest number: int largest=x[0]; for(int mm=0; mm<x.length; mm+=___) { ........if(_______<x[mm]) ........{ ............largest = x[mm]; ........} }

1 largest

int[] x={ 3, 1, 4, 1, 5, 9, 2 }; int[] y={ 0, 7, 3, 1, 9, 4, 9 }; for(int j=2; j<=5; j++) { ....System.out.print( x[ j ] - y[ j ] + " "); }

1 0 -4 5

for (int d = 1; d <= 20; d = d * 2) what are the values of d?

1 2 4 8 16

The last subscript in an array is always...

1 less than the number of elements

Chapter Objectives:

1) Define and use arrays for basic data organization. 2) Discuss bounds checking and techniques for managing capacity. 3) Discuss the issues related to arrays as objects and arrays of objects. 4) Explore the use of command-line arguments 5) Describe the syntax and use of variable-length parameter lists. 6) Discuss the creation and use of multidimensional arrays.

What is auto-boxing?

Conversion between primitive types and the corresponding wrapper classes is automatic.

Common Errors to Avoid

1. Using an invalid subscript. Java does not allow you to use a subscript value that is outside the range of valid subscripts for an array. 2. Confusing the contents of an integer array element with the element's subscript. An element's subscript and the value stored in the element are not the same thing. The subscript identifies an element, which holds a value. 3. Causing an off-by-one error. When processing arrays, the subscripts start at zero and end at one less than the number of elements in the array. Off-by-one errors are commonly caused when a loop uses an initial subscript of one and/or uses a maximum subscript that is equal to the number of elements in the array. 4. Using the = operator to copy an array. Assigning one array reference variable to another with the = operator merely copies the address in one variable to the other. To copy an array, you should copy the individual elements of one array to another. 5. Using the = operator to copy an array. Assigning one array reference variable to another with the = operator merely copies the address in one variable to the other. To copy an array, you should copy the individual elements of one array to another. 6. Reversing the row and column subscripts when processing a two-dimensional array. When thinking of a two-dimensional array as having rows and columns, the first subscript accesses a row and the second subscript accesses a column. If you reverse these subscripts, you will access the wrong element

array uses

1. collecting stats 2. representing the state of a game

Finding Maximum/Minimum Values

1. use a loop to examine each value 2. compare each value to the min/max so far 3. make the first element the smallest/largest 4. change smallest.largest as necessary

int[] x={ 3, 1, 4, 1, 5, 9, 2 }; for(int j=2; j<=5; j++) { ....System.out.print( x[ j ] + x[ j +1] + " " ); }

10 13 4 2

What is at location g[1][2][0]?10 What about g[0][1][1]? int[][][] = { { {0,12,4}, {4,16,5}, {8,20,6}}, {{2,14,7}, {6,18,8}, {10,22,9}} };

10 and 16

int[] x={ 3, 7, 1, 9, 4, 0, 2 }; int[] y={ 0, 7, 3, 1, 9, 4, 9 }; for(int k=4; k>=2; k--) { . . . . System.out.print( x[ k ] + y[ k ] + " " ); }

13 10 4

How many loops are necessary in the Bubble sort routine?

2

How many data points can array that's 2 x 3 x 4 hold?

24

How many data points can array that's 2x3x4 hold?

24 (2x3x4=24)

What type of an array would you use to hold the weight and height of students in the class of 2010?

2D [22][2] in this case the row is the student number, if you had 22 in the class

int[] x={ 3, 1, 4, 1, 5, 9, 2 }; int[] y={ 0, 7, 3, 1, 9, 4, 9 }; for(int j=2; j<4; j++) { ....System.out.print( x[ j ] - y[ j ] + " "); }

3 -6 1 0

int myArray[] = {3, 4, 5, 6}; for(int qq=0; qq<myArray.length; qq++) { ....if(myArray[qq]>4) ....{ ........break; ....} ....System.out.print(myArray[qq] + " "); }

3 4

If an array has 5 elements, what is the index value for the last item in the array?

4

If an array has 5 elements, what is the index value for the last item in the array?

4 (it starts at 0)

int[] x={ 3, 1, 4, 1, 5, 9, 2 }; for(int j=2; j<=5; j++) { ....if( j == 4 ) ....{ ........break; ....} ....System.out.print( " " + x[ j ] ); }

4 1

int[] x={ 3, 1, 4, 1, 5, 9, 2 }; for(int j=2; j<=5; j++) { ....if( j == 4 ) ....{ ........continue; ....} ....System.out.print( " " + x[ j ] ); }

4 1 9

int[] x={ 3, 7, 1, 9, 4, 0, 2 }; int[] y={ 0, 7, 3, 1, 9, 4, 9 }; for(int rr=2; rr<=5; rr++) { ....System.out.print( x[ rr ] + y[ rr ] + " "); }

4 10 13

for (int m = 0; m <= 9; m++) { . . . . if( m<4 ) . . . . { . . . . . . . .continue; . . . . } . . . .System.out.print(m + " "); }

4 5 6 7 8 9

What would x = d.length give for the value of x? d[ ] = {2,5,7,1,10};

5

for (int k = 5; k > 0; k--) { ....if( k<3 ) ....{ ........break; ....} ....System.out.print(k + " "); }

5 4 3

for (int k = 5; k >= 0; k--) what are the values of k?

5 4 3 2 1 0

What would x = d.length give for the value of x? (Look at #14)

5, because of the amount of characters

Suppose you are thinking of a number from 0 to 100, what is the first number that it's compared to if searching in binary?

50

How can Java methods have variable-length parameter lists?

A Java method can be defined to accept a variable number of parameters by using an ellipsis (...) in the formal parameter list. When several values are passed to the method, they are automatically converted to an array. This allows the method to be written in terms of array processing without forcing the calling method to create the array.

Wrapper class

A class that wraps primitive values in an object.

array

A collection of values, where all the values have the same type, and each value is identified by an index.

What is a command-line argument?

A command-line argument consists of data included on the command line when the interpreter is invoked to execute the program. Command-line arguments are another way to provide input to a program. They are accessed using the array of strings that is passed into the main method as a parameter.

Array

A data structure for storing a collection of data of the same type

flag variable

A flag variable, in its simplest form, is a variable you define to have one value until some condition is true, in which case you change the variable's value. It is a variable you can use to control the flow of a function or statement, allowing you to check for certain conditions while your function progresses.

Collection

A group of related elements that are stores together as a single unit.

command line

A java program receives its ______ _______ arguments in an array.

initializer list

A list of values delimited by braces and separated by commas, used to initialize the values stored in an array.

How are multidimensional arrays implemented in Java?

A multidimensional array is implemented in Java as an array of array objects. The arrays that are elements of the outer array could also contain arrays as elements. This nesting process could continue for as many levels as needed.

variable-length parameter list

A parameter list in a method header that allows a variable number of parameters to be passed in, which are stored in an array for processing.

nondeterministic

A program that always behaves differently, even when run multiple times with the same input.

deterministic

A program that does the same thing every time it is invoked.

array

A programming language construct used to organized objects into an indexed list.

Sequential Search Algorithm

A search algorithm is a method of locating a specific item in a larger collection of data. This section discusses the sequential search algorithm, which is a simple technique for searching the contents of an array - The reason -1 is returned when the search value is not found in the array is because -1 is not a valid subscript.

pseudorandom

A sequence of numbers that appear to be random, but which are actually the product of a deterministic computation.

What is an array?

A set of data of the same type referenced with a common name

Array initializer

A short hand notation to create and initialize an array Example: elementType[] arrayRefVar= [value0, value1,....]; Real life example: double[] myList = [1.9, 2.9, 3.4, 3.5];

Selection sort and binary search

A sorting algorithm is used to arrange data into some order. A search algorithm is a method of locating a specific item in a larger collection of data. The selection sort and the binary search are popular sorting and searching algorithms.

Arrays

A structure that can store many of the same kind of data together at once.

reduce

A traversal pattern that combines the elements of an array into a single value.

search

A traversal pattern used to find a particular element of an array.

The length field in a two-dimensional array

A two-dimensional array, however, has multiple length fields. It has a length field that holds the number of rows, and then each row has a length field that holds the number of columns

ArrayList<BankAccount> What is BankAccount?

A type parameter. You cannot use primitive types as type parameters in an ArrayList.

reference

A value (memory address) that indicates another value, like an array. In a state diagram, a reference appears as an arrow.

array element

A value stored in an array.

reference

A value that indicates another value, like an array. In a state diagram, a reference appears as an arrow.

alias

A variable that refers to the same object as another variable.

accumulator

A variable used to accumulate results during a traversal.

Traversing

Accessing each element of an array is called ___ an array.

String(StringBuilder builder)

Convert a StringBuilder into a String

What does this do? System.arraycopy(data, i, data, i + 1, data.length - i - 1); data[i] = x;

Adds a new element at position i into data, first moves all elements from i onward one position up. Then inserts the new value. Last element is lost.

unshift()

Adds new elements to the beginning of an array, and returns the new length

push()

Adds new elements to the end of an array, and returns the new length

splice()

Adds/Removes elements from an array

int compareTo(String anotherString)

Alphabetically compares two strings and returns value < 1 if this string comes before the argument string, 0 if they're equal, and value > if this string comes after

Linear Search

An algorithm for searching an array in which each element of the array is checked one after the other.

enhanced for loop

An alternative syntax for traversing the elements (values) of an array.

What does an array initializer list accomplish?

An array initializer list is used in the declaration of an array to set up the initial values of its elements. An initializer list instantiates the array object, so the new operator is not needed.

Definition of an array

An array is a sequence of values of the same type. They can hold both primitives and objects.

What is an array?

An array is an object that stores a list of values. The entire list can be referenced by its name, and each element in the list can be referenced individually based on its position in the array.

histogram

An array of integers where each integer counts the number of values that fall into a certain range.

How is an array of objects created?

An array of objects is really an array of object references. The array itself must be instantiated, and the objects that are stored in the array must be created separately.

Dynamic Array

An array that varies in size at run time.

multidimensional array

An array with more than one index dimension.

one-dimensional array

An array with one indexed dimension; a simple list of values.

two-dimensional array

An array with two indexed dimensions; it can be thought of as a table with rows and columns.

anonymous arrays

An array without name is known as ______ ______ in java. As the array do not have any name so it can be used only once. _______ _____ is passed as an argument of method. _____ _____ is created and initialized in the same line.

What is an array's element type?

An array's element type is the type of values that the array can hold. All values in a particular array have the same type, or are at least of compatible types. Thus we might have an array of integers, or an array of boolean values, or an array of Dog objects, and so on.

Can an entire array be passed as a parameter? how is this accomplished?

An entire array can be passed as a parameter. Specifically, because an array is an object, a reference to the array is passed to the method. Any changes made to the array elements will be reflected outside of the method.

off-by-one error

An error in which an array index does not process the correct range of values, usually resulting in one less element being processed or an attempt being made to process one more element.

Array-Index-Out-Of-Bounds-Exception

An exception thrown when an invalid array index is used.

index

An integer used to specify a specific element in an array.

index

An integer variable or value used to indicate an element of an array.

String(char[] array)

Convert a char array into a String

String toLowerCase()

Converts String to all lowercase

String toUpperCase()

Converts String to all uppercase

What is an off-by-one error? How is it related to arrays?

An off-by-one error occurs when a program's logic exceeds the boundary of an array (or similar structure) by one. These errors include forgetting to process a boundary element, as well as attempting to process a nonexistent element. Array processing is susceptible to off-by-one errors because their indexes begin at zero and run to one less than the ssize of the array.

ArrayList vs Array: What are differences?

Array is an ordered list of values. Each array has a name by which it can be referenced. Difference between array and arraylist in java include eight points namely Resizable, Performance, Traversal ,Primitives , Length , Type-Safety, Adding elements , Multi-dimensional. 1. Resizable : Array is static in size that is fixed length data structure, One can not change the length after creating the Array object.

"thu"

Array named days has days of the week. The elements are "mon", "tue", "wed", ... "sun". What is days[3]?

String

ArrayList <_________> firstName

ArrayList class

ArrayList is a class in the Java API that is similar to an array and allows you to store objects. Unlike an array, an ArrayList object's size is automatically adjusted to accommodate the number of items being stored in it - • An ArrayList object automatically expands as items are added to it. - • In addition to adding items to an ArrayList, you can remove items as well. - • An ArrayList object automatically shrinks as items are removed from it. *The ArrayList class is in the java.util package, so the following import statement is required: import java.util.ArrayList;

new ArrayList<String>()

ArrayList<String> areaItems = ________

Syntax for constructing an ArrayList?

ArrayList<type> reference = new ArrayList<type>();

Describe the process of creating an array. When is memory allocated for the array?

Arrays are objects. Therefore, as with all objects, to create an array we first create a reference to the array (its name). We then instantiate the array itself, which reserves memory space to store the array elements. The only difference between a regular object instantiation and an array instantiation is the bracket syntax.

number

Arrays are the most efficient way to store a collection of a known _____ of items

Array variables

Arrays can be used in the same way as a regular variable. myList[2] = myList[0] + myList[1]; This will assign myList[2] the values of myList[0] and myList[1].

copyOf syntax

Arrays.copyOf(<source array>, <length>);

Finding max or min algorithm.

BankAccount largestYet = accounts.get(0); for (int i = 1; i < accounts.size(); i++) { BankAccount a = accounts.get(i); if (a.getBalance() > largestYet.getBalance()) largestYet = a; } return largestYet;

you cannot have arrays with various primitive types or values because why?

Because of the size of the elements. Make sure they are all of the same type.

What does this do? arrayListReference.add(object);

Called the add method. Adds an object to the end of the array list and increases the size.

What does this do? arrayListReference.add(i, a);

Called the add method. Adds object a at index i and moves all elements by one position, from the current element at position i to the last element in the array list. After each call to the add method, the size of the array list increases by 1.

What does this do? arrayListReference.remove(i);

Called the remove method. Removes the element at position i, moves all elements after the removed element down by one position, and reduces the size of the array list by 1.

What does this do? arrayListReference.set(i, a);

Called the set method. Overwrites index i with a. Nothing else is moved. Size stays the same.

What does this do? arrayListReference.size();

Called the size method. Returns the size of the array list. The last valid index is arrayListReference.size() - 1.

forEach()

Calls a function for each array element

some()

Checks if any of the elements in an array pass a test

every()

Checks if every element in an array pass a test

isArray()

Checks whether an object is an array

Collections framework

Classes for implementing collections.

create an array of letters: of string objects: of song objects: of card object: of boolean objects:

Declaring Arrays I An array of letters char[] letters; letters = new char [26]; I An array of String objects String [] dictionary = new String [480000]; I An array of Song objects Song[] playlist = new Song [3]; I An array of Card objects Card[] deckOfCards = new Card [52]; I An array of boolean objects boolean [] lightSwitches = new boolean [100];

Declaring an array variable

Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement as shown below .//This syntax is preferred elementType [] arrayRefVar = new elementType[arraySize]; Here is an example: double [] myList = new double[10]; The statement declares an array variable myList, creates an array of 10 elements of double type, and assigns its reference to myList.

Off-by-One Errors

During the loop's execution, the variable index takes on the values 1 through 100, when it should take on the values 0 through 99. As a result, the first element, which is at subscript 0, is skipped. In addition, the loop attempts to use 100 as a subscript during the last iteration. Because 100 is an invalid subscript, the program will throw an exception and halt.

Index Value

Each array starts with 0 being this as the first item, 1 being this as the second item, and so on.

How is each element of an array referenced?

Each element in an array can be referenced by its numeric position, called an index, in the array. In Java, all array indexes begin at zero. Square brackets are used to specify the index. For example, nums[5] refers to the sixth element in the array called nums.

T/F - An array's size declarator can be a negative integer expression.

False

T/F - The first size declarator in the declaration of a two-dimensional array represents the number of columns. The second size declarator represents the number of rows.

False

fill()

Fill the elements in an array with a static value

ArrayList is a ___ class

Generic class.

ArrayList is a ___ class.

Generic class.

xyz[ xyz.length -1] = 9;

Given array named xyz. Assign 9 to the last element in xyz .

Explain how a linear search works

Goes through items and compares

default values

If <length> is longer than the length of the source array, the extra elements are given the _____ _______.

only

If <length> is shorter than the length of the source array, _____ the first elements of that array are copied.

ArrayList

If you need to resize an array often, you are better of using an ______ object.

Returning Arrays from methods

In addition to accepting arrays as arguments, methods may also return arrays. public static double[] getArray() { double[] array = { 1.2, 2.3, 4.5, 6.7, 8.9 }; return array; } values = getArray();

information, consecutive memory

In java, arrays are objects so they contain more ____, but the data is stored in ______

Processing Array Elements

Individual array elements are processed like any other type of variable. grossPay = hours[3] * payRate; - When using increment and decrement operators, be careful not to use the operator on the subscript when you intend to use it on the array element

Explain how a binary search works starts with a sorted list and cuts in half over and over while making comparisons

It cuts the list in half and then in half over and over again, comparing if the target value is above or below the middle value.

What does the following do, y = test.equals("sup"), and what type of variable is y?

It returns true if there is a match. The variable "y" is boolean

How does a linear search work?

It sequentially checks all the values until a match is found.

What is an irregular array and give an example of declaring one called bus for a bus schedule that just runs M, W, F for 4 times each day, on Tues, Thurs, and Sat twice, and Sun once.

It would be an array that has a different number of columns for each row. int bus[][] = new int[7][]; bus[0] = new int[4]; //on Mondays you can hold 4 data pts bus[1] = new int[2]; // on Tuesday, 2 data pts bus[2] = new int[4]; //Wednesday hold 4 data points //etc.

join()

Joins all elements of an array into a string

concat()

Joins two or more arrays, and returns a copy of the joined arrays

Which way can be used if the data is unorganized?

Linear

List two ways to search a data set

Linear and Binary

What are the two ways to search a data set?

Linear, and Binary

traversal

Looping through the elements of an array (or other collection).

How are arrays implemented?

Methods

An array of Size N is indexed from 0 to what?

N - 1

This is the typical number of comparisons performed by the sequential search on an array of N elements (assuming the search values are consistently found).

N/2

Can the same array hold both the name of a student and their grades?

No mixing

Can the same array hold both the name of a student and their grades?

No, you cannot mix types

Is arrayListReference[i] valid to get an element?

No. You must use the get method. arrayListReference.get(i)

What are strings in Java?

Objects

Array Info.

Once an array is created it's size is fixed. An array reference variable is used to access the elements in an array using index.

How many different variable types can the same array hold?

One

element

One of the values in an array. The[]operator selects elements.

What makes an array list different from an array?

Only holds objects. Can grow and shrink as needed. Supplies methods for inserting and removing objects. More overhead.

reduce()

Reduce the values of an array to a single value (going left-to-right)

reduceRight()

Reduce the values of an array to a single value (going right-to-left)

What is regression testing?

Regression testing involves repeating previously run tests to ensure that known failures of prior versions do not appear in new versions of the software.

findIndex()

Returns the index of the first element in an array that pass a test

int indexOf(int ch)

Returns the index of the first occurrence of the specified character

int indexOf(String s)

Returns the index of the first occurrence of the specified substring

int lastIndexOf(int ch)

Returns the index of the last occurrence of the specified character

int lastIndexOf(String s)

Returns the index of the last occurrence of the specified substring

int length()

Returns the length of the String

What does ch = data.charAt(0) in the string "open now." return?

Returns the o

valueOf()

Returns the primitive value of an array

String trim()

Returns the string without leading or trailing whitespace

find()

Returns the value of the first element in an array that pass a test

boolean endsWith(String suffix)

Returns true if String ends with the specified String

boolean equals(Object anObject)

Returns true if String equals another object. Use this to see if two strings are equal.

equals method

Returns true if a and b have the same length and the elements of in corresponding indexes match and false otherwise.

boolean isEmpty()

Returns true if length of string is 0

boolean contains(String s)

Returns true if the String contains the specified String

reverse()

Reverses the order of the elements in an array

String str="Soda"; for (int h = 0; h < str.length(); h++) { ....System.out.print( str[ h ] + " "); }

S o d a

What does this print? int[] x={ 3, 7, 1, 9, 4, 0, 2 }; int[] y={ 0, 7, 3, 1, 9, 4, 9 }; for( int pp= 1; pp<=5; pp=pp+2 ) { . . . . if( x[ pp ] > y[ pp ] ) . . . . { . . . . . . . . System.out.print("BIG ") . . . . } . . . . else . . . . { . . . . . . . . System.out.print( "SMALL " ); . . . . } }

SMALL BIG SMALL

What does this print? int[] x={ 3, 7, 1, 9, 4, 0, 2 }; int[] y={ 0, 7, 3, 1, 9, 4, 9 }; for( int j=1; j<=5; j++ ) { ....if( x[ j ] > y[ j ] ) ....{ ........System.out.print("BIG ") ....} ....else ....{ ........System.out.print( "SMALL " ); ....} }

SMALL SMALL BIG SMALL SMALL

indexOf()

Search the array for an element and returns its position

lastIndexOf()

Search the array for an element, starting at the end, and returns its position

slice()

Selects a part of an array, and returns the new array

for

Since the elements are indexed starting at 0 and going to arrayName.length - 1, we can print all the elements of an array using a ___ loop:

static void sort(Object[] arr)

Sorts an array of Objects according to their natural ordering

static void sort(int[] arr)

Sorts an int (or any primitive type) array into ascending order. Doesn't return anything

sort()

Sorts the elements of an array

Give an example of a need to use a 3-d array

Storing height, weight, and blood pressure

How can the contents of a string variable be altered?

String are immutable, so their contents can't be altered

Create and fill an array with the strings "This", "is" "great"

String data[] = {"This", "is", "great"};

Create and fill an array with the strings "This", "is", and "great"

String data[] = {"This", "is", "great"};

Create a string that has no characters

String empty = "";

3

String middleName = "Jane"; String [] myNames = { "Mary", middleName, "Watson" }; how many element will the above array have?

Create an appropriate array to hold the names and phone numbers of 3 people.

String numbers[][] = { {"Tom", "555-3322"}, {"Sam", "555-8976"}. {"Cole", "596-2142"} };

vararg parameter

The ellipsis (three periods) that follows the data type indicates that numbers is a special type of parameter public static int sum(int... numbers)

What does an enhanced for loop (for each) do?

The enhanced for loop traverses all elements of a collection. You can't assign values with a for each loop.

Finding the lowest value

The following code finds the lowest value in the array int lowest = numbers[0]; for (int index = 1; index < numbers.length; index++) { if (numbers[index] < lowest) lowest = numbers[index]; }

Array initializer Info

The new operator is not used in the array initializer syntax. With array initializers you cannot split the code otherwise it will cause an error.

Type Parameter

The part of an ArrayList statement that informs the compiler of what type of objects the ArrayList can contain. For example, <String>.

Autoboxing

The process in which a primitive is automatically converted to a wrapper class object.

Auto-unboxing

The process in which a primitive is automatically extracted from a wrapper class object.

bounds checking

The process that ensures that an index is in the valid range for teh array being referenced. Java performs automatic bounds checking.

Unicode

The sixteen-bit digital code used to represent every letter and symbol.

element type

The type of data that can be stored as an element in a particular array.

Why are arrays convenient?

They group together related data, organize data, and assist in the sorting and searching of data

Element

This is one of the data items in an array.

The "NEW" operator

This operator allocates space for the number of elements indicated in brackets.

dataType [] arrayName;

To declare a reference to the array:

Generics

Used for communicating to the compiler the type of data stores in an ArrayList.

the inequality

What would you change to find the smallest instead of the largest?

Passing two-dimensional arrays to methods

When a two-dimensional array is passed to a method, the parameter must be declared as a reference to a two-dimensional array private static void showArray(int[][] array)

Initializing a two-dimensional array

When initializing a two-dimensional array, you enclose each row's initialization list in its own set of braces. int[][] numbers = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };

Ragged arrays

When the rows of a two-dimensional array are of different lengths, the array is known as a ragged array - You create a ragged array by first creating a two-dimensional array with a specific number of rows, but no columns.

Command-line arguments and variable-length argument lists

When you invoke a Java program from the operating system command line, you can specify arguments that are passed into the main method of the program. In addition, you can write a method that takes a variable number of arguments. When the method runs, it can determine the number of arguments that were passed to it and act accordingly

Explain the concept of array bounds checking. What happens when a Java array is indexed with an invalid value?

Whenever a reference is made to a particular array element, the index operator (the brackets that enclose the subscript) ensures that the value of the index is greater than or equal to zero and less than the size of the array. If it is not within the valid range, an ArrayIndexOutOfBoundsException is thrown.

Can an array hold strings?

Yes

If you have two arrays, one called apple, and one orange, does this work: apple = orange;

Yes

Can a string have just one character? Show an example and show the same answer but with a different variable type.

Yes String one = "A"; char one = 'A';

Does auto-boxing work inside arithmetic expressions?

Yes.

Do you have to import the ArrayList class to use it?

Yes. import java.util.ArrayList

When you construct an ArrayList object, it has a size of?

Zero.

array

a data structure that stores a sequence of values of the same type

same type

a python list can have elements of many types but an array must have the

How to find the number of elements in: a) an Array b) an ArrayList c) a String

a) .length b) .size() c) .length()

Wrapper classes for: a) boolean b) int c) double

a) Boolean b) Integer c) Double

Wrapper classes for: a) boolean b) int c) double

a) Boolean b) Integer c) Double

To insert an item at a specific location in an ArrayList object, you use this method.

add

Suppose you have two arrays num1 and num2. What does num1 = num2 do?

all values at the various positions of num1 match num2, you are causing num1 to reference num2

movie is an array. It has many items. Set amount = the number of items in movie.

amount = movie.length;

a 2d array is what?

an array of arrays (like rows & columns); example: int[][] table = new int[3][5]; //note. table.length is rows table[i].length is the [i]'th row in the table.

null

any object reference default value

A partially filled

array is normally used with an accompanying integer variable that holds the number of items stored in the array. - If a partially filled array is passed as an argument to a method, the variable that holds the count of items in the array must also be passed as an argument. Otherwise, the method will not be able to determine the number of items that are stored in the array

datatype [] arrayName = { value0, value1, ...};

array specific instantiation syntax

int [] scores = new int[5]; break this array down: what is each part ?

array type: int [] array name: scores creates new array object:new type and size: int[5];

How do you get the last valid index of an ArrayList?

arrayListReference.size() - 1

How do you get the last valid index of an ArrayList?

arrayListReference.size() - 1.

How to obtain the size of an array

arrayRefVar.length. For example: myList.length is 10

Assign values to array elements

arrayRefVar[index] = value; For example: myList[0] = 5.6; myList[1] = 4.5; ......... myList[9] = 98.13

objects

arrays are

efficient

arrays are more ____ than lists

oldest, most basic

arrays are one of the ____ and ____ __ _data structure in cs

specifying

arrays can also be instantiated by _____ a list of initial values

contiguous memory allocation

assigns the consecutive blocks of memory to a process requesting for memory

noncontiguous memory allocation

assigns the separate memory blocks at the different location in memory space in a nonconsecutive manner to a process requesting for memory.

Which search routine is faster for sorted data?

binary

This search algorithm repeatedly divides the portion of an array being searched in half.

binary search

false

boolean default value

equals syntax

booleanArrays.equals(a, b)

_____ ____ ensures that an index used to refer to an array element is in range.

bounds checking

When initializing a two-dimensional array, you enclose each row's initialization list in...

braces

0

byte, short, int default values

candy is an array. Set the last item to "fruit roll".

candy[ candy.length-1 ] ="fruit roll";

null character

char default value

How do you declare a one-dimensional array to hold ten characters?

char sample[ ] = new char [10];

How do you declare a one-dimensional array to hold ten characters?

char sample[] = new char[10]

size=cup.length;

cup is an array with values like 1.0, 2.5, 4.2 cc. Set size = the number of elements in cup.

cup[9]=13;

cup is an array with values like 1.0, 2.5, 4.2 cc. Set the 10th element to 13 cc.

cup[0]=23;

cup is an array with values like 1.0, 2.5, 4.2 cc. Set the 1st element to 23 cc.

cup[1]=3.5;

cup is an array with values like 1.0, 2.5, 4.2 cc. Set the 2nd element to 3.5 cc.

cup[ cup.length - 1 ]=9;

cup is an array. It has many elements like 2.2, 3.3, 14.5 cc. Set the last element to 9 cc.

cup is an array. It has many elements like 2, 3.3, 4 cc. Set the last element to 9 cc.

cup[ cup.length - 1 ]=9;

cup is an array. It has more than 50 sizes, like 1, 2.5 cc. Set the 2nd element to 3.5 cc.

cup[1]=3.5;

cup is an array. It has more than 50 sizes, like 1, 2.5, 8.2 cc. Set the 10th element to 13 cc.

cup[9]=13;

one

declaration and instantiation can be done in ___ step

friends[ ] xyz = new friends[10]

declare array of to friends called xyz

default values for arrays

default value for numeric primitive data types is 0 \u0000 for char types and false for boolean types.

no

does quick sort create a new array?

0.0d

double default value

When creating arrays, it's good practice to do what with each addition to the array.

double the size so we don't have to do the copying again.

Declare cup array. It has 50 elements like 2, 3.3, 4 cc.

double[] cup=new double[50];

Declare cup array. It has elements 2, 3.3, 4 cc.

double[] cup={2, 3.3, 4};

anonymous arrays syntax

double[] dailyMiles; dailyMiles = new double {170.3, 278.9, 283.2, 158.0, 433.3};

How to grow an array that has run out of space.

double[] newData = new double[2 * data.length]; System.arraycopy(data, 0, newData, 0, data.length); data = newData;

Syntax of copying an array.

double[] prices = (double[]) data.clone();

length

each array has a read-only integer instance variable named ____ which holds the number of elements in an array

element

each variable on the array is an

What are some advantages of using arrays to hold data?

easily manipulated, sorted easily, tallied easily, searched easily

Suppose the test is the string supal, what value does y have?

false all the characters must match

length

first check for if arrays are the same

declaring the reference to the array

first step of creating an array

When an array is created it has a ____ size. The size of the array is a public constant named ___.

fixed, length

0.0f

float default value

Syntax of a for-each loop.

for (Type variable : collection) statement Example: for (double e : data) sum = sum + e;

Array variables for loop

for(int i = 0; i < myList.length; i++) { myList[i] = 1; }

Give some examples where you might use arrays

grades, bus schedule, race times, wind data

through an index

how do arrays allow random access of elements?

arrayName[exp]

how to access an element of an array

use length - 1

how to access the last element of an array?

create a new list and use a for loop

how to create a copy of an array that is not an alias?

arrayName[exp] = value;

how to set indexes in an array to values?

snack is an array. It has more than 50 items. Set howMany = the number of items in snack.

howMany=snack.length;

What describes the position of an element within an array?

index

What is the term that describes the items that is used to access a value in an array?

index

What message do you get if you go beyond the index range of an array?

index out of bounds

for (int p = 0; p != 9; p = p + 2) what are the values of p?

infinite loop

An ____ list can be used, instead of the new operator, to instantiate an array object.

initializer

How can you declare and initialize a one-d array called d with the values {2, 5, 7, 1, 10} using one line of code?

int d[ ] = {2,5,7,1,10};

How can you declare and initialize a one-d array called d with the values {2, 5, 7, 1, 10} using one line of code?

int d[] = {2,5,7,1,10};

What type of array would you use to hold all of your final exam grades (assume just 1st and 2nd semester) for all of your high school years. Write a piece of code to declare it.

int g[][][] = new int[3][2][4]

What type of array would you use to hold all of your final exam grades (assume just 1st and 2nd semester) for all of your high school years. Write a piece of code to declare it.

int g[][][] = new int[3][2][4]; this is a 3 dimensional array

What single line of code can be used to declare a 1D array called temp to hold 3 items?

int temp[] = new int[3];

Summing the rows of a two-dimensional array

int total; // Accumulator for (int row = 0; row < numbers.length; row++) { // Set the accumulator to 0. total = 0; // Sum a row. for (int col = 0; col < numbers[row].length; col++) total += numbers[row][col]; // Display the row's total. System.out.println("Total of row " + row + " is " + total); }

Declare x array to hold elements are 1.2, 2.4, 3.6, 4.8.

int x[] = {1.2, 2.4, 3.6, 4.8 };

this finds the smallest integer in array z public int smallestInt(_______ _________) { ....int small; ........ ........ ........ ....return small; }

int[] z

money[2]=3;

int[] money={34, 21, 5, 9, 12, 43, 2, 17, 8}; Replace 5 with 3

Initialize an integer array named primes with five values.

int[] primes = new int[] { 2, 3, 5, 7, 11 };

Example of hard coding numbers into an array (2x3x2)

int[][][] = { { {0,12,4}, {4,16,5}, {8,20,6}}, {{2,14,7}, {6,18,8}, {10,22,9}} };

When we try to access an element in an array out of bounds what happens? Which is called what?

java interpreter throws an ArrayIndexOutOfBondsException called bounds checking

find the largest number: int huge=myArray[0]; for(int ____=0; k<_________; k++) { ........if(huge<myArray[k]) ........{ ............huge = myArray[k]; ........} }

k myArray.length

find the largest number: int largest=x[0]; for(int i=0; i<x.length; i++) { ........if(_______<x[i]) ........{ ............largest = _______; ........} }

largest x[i]

This array field holds the number of elements that the array has.

length

0L

long default value

block of contiguous memory

many implementations of arrays use a

find the largest number: int largest=g[0]; for(int mm=0; mm<g.length; mm=___) { ........if(_______<g[mm]) ........{ ............largest = g[mm]; ........} }

mm+1 largest

int[] money={34, 21, 5, 9, 12, 43, 2, 17, 8}; Replace 5 with 3

money[2]=3;

int[] money={34, 21, 5, 9, 12, 43, 2, 17, 8}; Replace 9 with 3

money[3]=3;

find the largest number: int huge=myArray[0]; for(int k=0; k<_________; k++) { ........if(huge<myArray[k]) ........{ ............huge = _________; ........} }

myArray.length myArray[k]

Write a piece of code to initial an array called g that's 2X3X2 to even numbers starting with zero.

n=0; for (int d=0; d< 2; d++) for (int c=0; c< 3; c++) for (int r=0; r<2; r++) g[r][c][d] = n; n = n + 2;

Add an item to an ArrayList

nameList.add("James"); nameList.add("Catherine"); nameList.add("Bill");

Summing the columns of a two-dimensional array

nested loops. The outer loop controls the column subscript and the inner loop controls the row subscript. The inner loop calculates the sum of a column, which is stored in an accumulator.

In Java, an array is an ___ that must be instantiated.

object

How are arrays implemented?

objects

What are strings in Java? objects, arrays, or characters?

objects

. How many loops are necessary to find the largest number in an array?

one

An entire array can be passed as a ____ , making the formal parameter an ___ of the original.

parameter, alias

double[] price={ 1.2, 3.4, 8.3, 2.5, 0.1, 7.7}; Print array backward from the last element to the first? for (int h = ________; h>0 ; ______ ) { ....System.out.print( str[ h ]); }

price.length()-1 h>0 h--

Finding a value algorithm.

public class Bank { public BankAccount find(int accountNumber) { for (BankAccount a : accounts) { if (a.getAccountNumber() == accountNumber) // Found a match return a; } return null; // No match in the entire array list } . . . }

Counting matches algorithm.

public class Bank { public int count(double atLeast) { int matches = 0; for (BankAccount a : accounts) { if (a.getBalance() >= atLeast) matches++; // Found a match } return matches; } . . . private ArrayList<BankAccount> accounts; }

a method for copying color values with an array: deep copy.

public static Color[] workWithArrays(Color[] myColor) { Color [] newColors = new Color[myColor.length]; for (int i = 0; i < myColor.length; i++ { Color old = myColor[i]; //deep copy newColors[i] = new Color(old.getRed(), old.getGreen(), old.getBlue()); } return newColors; }

studentName.add( "Tiger" )

put Tiger in arraylist called studentName

Give an example of a need to use a 3-d array.

recording height, weight, blood pressure

Instantiating an array of objects reserves room to store ____ only. The objects that are stored in each element must be ____ separately.

references, instantiated

To delete an item from an ArrayList object, you use this method.

remove

Suppose data is the string "open now." What does ch = data.charAt(8) return?

returns the character

What does ch = data.charAt(0) return?

returns the o

compare each element

second check for if arrays are the same

instantiating the array

second step of creating an array

This search algorithm steps through an array, comparing each item with the search value.

sequential search

To determine the number of items stored in an ArrayList object, you use this method.

size

In an array declaration, this indicates the number of elements that the array will have.

size declarator

box is an array. It has many sizes, like 1, 2.5, 7.2 cc. Set size = the number of elements in box.

size=box.length;

cup is an array. It has many sizes, like 1, 2.5, 7.2 cc. Set size = the number of elements in cup.

size=cup.length;

String[] snack=new String[50];

snack is an array of 50 food names. Declare this array.

snack[0]="water";

snack is an array with elements like "fruits", "candy", "chips". Set the 1st element to "water".

snack[10]="gum";

snack is an array. It has more than 50 items, like "fruits", "candy", "chips". Set the 11th item to "gum".

snack[1]="water";

snack is an array. It has more than 50 items, like "fruits", "candy", "chips". Set the 2nd item to "water".

howMany=snack.length;

snack is an array. It has more than 50 items. Set howMany = the number of items in snack.

snack[ snack.length-1 ] ="water";

snack is an array. Set the last item to "water".

snack is an array. Set the last item to "water".

snack[ snack.length-1 ] ="water";

snack is an array. It has more than 50 items, like "fruits", "candy", "chips". Set the 1st element to "water".

snack[0]="water";

snack is an array. It has more than 50 items, like "fruits", "candy", "chips". Set the 11th item to "gum".

snack[10]="gum";

snack is an array. It has more than 50 items, like "fruits", "candy", "chips". Set the 2nd item to "water".

snack[1]="water";

boolean

sort works for primitive types except

index

specifies the position of each element in the array

the name of the array

the area of memory, created by the instantiation of the array, has one name

primitive types, classes

the data type in an array can be any of java's ______ or _____

How can you tell if a character is capitalized?

the decimal value is between 65 and 90 inclusive

accessing an array, we must use valid index. The valid index of an array named scores is what?

the range of valid indexes is 0 to scores.length -1;

fixed size

the size of a python list can change, but an array has a

collection

the variable in a for each loop must be the type of the elements in the ________

Why are arrays convenient?

they group together related data, they organize data, they assist in the sorting and searching of data

arrayName = new dataType[ size ];

to instantiate an array

Suppose data is the string "Broken" What is the value of x in the expression x = data.compareTo("Summer") ?

x will be some negative number because broken is shorter than summer

Suppose data is the string "Broken". What is the value of x in the expression x = data.compareTo("Summer"); ?

x will be some negative number, because there is no match

find the largest number: int largest=x[0]; for(int mm=0; mm<_________; ______) { ........if(largest<x[mm]) ........{ ............largest = x[mm]; ........} }

x.length mm++

Look at this code. int[] x={ 3, 7, 1, 9, 4, 0, 2 }; int[] y={ 0, 7, 3, 1, 9, 4, 9 }; for(int m=_________; ________; m--) { ........System.out.print(x[ m ] + " and "); ........System.out.println( y[ m ]); } Fill the blank so that it prints 2 and 9 0 and 4 4 and 9

x.length-1 m>=4

You have an array of 77 whole numbers named xyz. Assign -1 to the last element in xyz .

xyz[76] =-1;

How can you search for a period in a sentence?

y = sentence.indexOf(".") OR ch = sentence.charAt(".");

How can you search for a period in a sentence?

y = sentence.indexOf("."), ch = sentence.charAt(".");

find the largest number: int big=y[0]; for(int i=0; i<_________; i++) { . . . . if(big<y[i]) . . . . { . . . . ______ = y[i]; . . . . } }

y.length big

find the largest number: int big=y[0]; for(int i=0; i<_________; i++) { ........if(big<y[i]) ........{ ............______ = y[i]; ........} }

y.length big

diamond operator

you are no longer required to write the data type in the part of the statement that calls the ArrayList constructor. Instead, you can simply write a set of empty angled brackets ArrayList<String> list = new ArrayList<>();

first

you can only specifically instantiate an array when it is ___ declared

insert

you may ____ into the middle of a python list, but not into an array

concatenate

you may ______ a python list, but not an array

Suppose data is the string "finish now". What does the following do? z = data.length(); What type is the variable z?

z is an integer and in this case z = 10

What are parallel arrays?

Two different arrays that should be combined into one array containing objects.

What is a 2D array?

Two-dimensional arrays form a tabular, two-dimensional arrangement. You access elements with an index pair a[i][j].

What does System.arraycopy do?

Use the System.arraycopy method to copy elements from one array to another.

How do you copy the elements of an array?

Use the clone method to copy the elements of an array. Has a return type of Object.

1 2 3 4 5

What is the output?

16

What is the output?

3.0 4.5 1.0 2.5 5.0 3.0 2.0 3.0

What is the output?

4.5 5.0

What is the output?

42.0

What is the output?

5

What is the output?

6

What is the output?

Creating Arrays

When you declare an array in Java the array variable does not allocate any space in memory for the array. It only creates a storage location for the reference to the array. If a variable does not contain a reference to the array the variable is null. You can not assign elements to an array unless it has already been declared.

If you have two arrays, one called apple, and one orange, does this work: apple = orange:;

Yes

What is an array?

a set of data of the same type referenced with a common name

How to find the number of elements in: a) an Array b) an ArrayList c) a String

a) .length b) .size() c) .length()

What is an irregular array and give an example of declaring one called bus for a bus schedule that just runs M, W, F for 4 times each day, on Tues, Thurs, and Sat twice, and Sun once.

an array that has a diff num of columns for each row int bus[][] = new int[7][]; bus[0] = new int[4]; //on Mondays you can hold 4 data pts bus[1] = new int[2]; // on Tuesday, 2 data pts bus[2] = new int[4]; and so on

Syntax for array element access

arrayReference[index] Ex. data[2]

How do you access the last index of an array?

arrayReference[length - 1]

Explain what a Bubble sort is and how does it word? How many loop do you need?

compares values at two index locations and does a swap if necessary, it repeats this over and over, need two loops

Syntax for creating an array with 3 rows and 3 columns.

final int ROWS = 3; final int COLUMNS = 3; String[][] board = new String [ROWS][COLUMNS];

Suppose data is the string "BrokenBroken" What is the value of x in the expression x =data.lastIndexOf("on")?

x = -1 since it's not found

. Suppose data is the string "BrokenBroken" What is the value of x in the expression x =data.lastIndexOf("en")?

x = 10 (the last makes it find the last en)

Suppose data is the string "BrokenBroken" What is the value of x in the expression x =data.indexOf("en") ?

x = 4 finds the first match

. If data = "Z", what is the value of x in the expression x = data.compareTo("B") ?

x = some positive number (x=0? @Nov2 ex 2 notes)

If x = bus.length, and y = bus[0].length, z = bus[1].length, what are the values for x , y, and z?

x =7, y = 4, z = 2

Can an array hold strings?

yes

Suppose data is the string "finish now" What does the following do, z = data.length(), and what type is the variable z?

z is an integer and in this case z = 10

Suppose data is the string "Broken" What is the value of part in the expression part =data.substring(3,6)? What type of variable is part?

part would be a string and in this case ken

What does the following do, y = test.equals("sup"), and what type of variable is y?

return true if match, the variable y is boolean

Explain how a binary search works

starts with a sorted list and cuts in half over and over while making comparisons

How can the contents of a string variable be altered?

string are immutable, contents can't be altered

How can you tell if a character is capitalized?

the decimal value is between 65 and 90 inclusive (I think this is referring to the ascii chart)

What type of an array would you use to hold the weight and height of students in the class of 2010?

two dimension [22][2] in this case the row is the student number, if you had 22 in the class

Syntax for initializing an array

typeName[] arrayReference = new typeName[length] Ex. double[] data = new double[10];

Suppose you are thinking of a number in a binary sort from 0 to 100, what is the first number that it's compared to?

50

The proper syntax to declare an array in Java

//Preferred syntax double[] myList; //This syntax is allowed but not preferred. //This syntax comes from the programming language C/C++ double myList[];

What kind of number is the index value for an array?

0 or a positive integer (no negatives or decimals)

What is a test suite?

A test suite is a set of tests for repeated testing.

Referencing an array

After an array variable is declared, you can create an array by using the new operator and assign its reference to the variable with the following syntax. //Syntax is below arrayRefVar = new elementType[arraySize]; The statement does two things. 1- It creates an array using new elementType[arraySize]; 2-It assigns the reference of the newly created array to the variable arrayRefVar.

What does an array variable do?

An array variable stores a reference to the array. Copying the variable yields a second reference to the same array.

Index

An integer value used to specify the position of an element in an array. The array index is an int value starting with the value 0 for the first element. 1 for the second, and so on.

Which way can be used if the data is organized?

Binary

What does this do? double[] data = new double[10]; . . . // Fill array double[] prices = data;

Both arrays are now pointing to the same reference.

Give three examples where you might use arrays

Grades, bus schedule, race times, wind data

What is the term that describes the items that is used to access a value in an array?

Index

What message do you get if you go beyond the index range of an array?

Index out of bounds

What does this do? System.arraycopy(data, i + 1, data, i, data.length - i - 1);

Removes an element at position i.

Suppose data is the string "open now." What does ch = data.charAt(8) return?

Returns the character

List two ways to construct a string.

String str = new String("Hello"); String str = "Helllo";

What field returns the number of elements in an array?

The length field. It is an instance variable of the array.

Write a method to find the minimum value in a one dimensional array.

int min = 10000; for (int i=0; i< 10; i++) if (sample[i] < min) min = sample[i];

Even though will typically use one step to declare an array, the creation of an array is a two step process, what are the two steps?

int sample[ ]; sample = new int[10]

What single line of code can be used to declare a one D array called temp to hold 3 items?

int temp = new int[3];

What type of an array would you use to hold the hours you work each day for a part time job (assume you work diff numbers of hours each day)?

irregular

List two advantages of storing data with arrays

it's easily manipulated, sorted easily, tallied easily, searched easily


संबंधित स्टडी सेट्स

Chapter 2 Overview of the Data Mining Process ISDS 574

View Set

BIO 169 - Exam 2: Cardiovascular & Lymphatic Systems & Immunity

View Set

Chapter 9: Levels of Disease Prevention

View Set

Hematology Chapter 11 Review Questions

View Set

Man. of Strategy Final Test Ed. 5 Chapter 10

View Set

development chapter 2 assignment 2

View Set