Chapter 07.pptx

advertisement

Introduction to Data Structures

- how to search and sort through data -

Arrays and Array Lists

Chapter 7

Objects and data structures

An object is a simple data structure

A data structure is an organized collection of related data

An array is a very important data structure and a variant exists in every programming language

We covered Arrays in section 3.8 and 5.1.4

• A numbered sequence of elements

• All elements are like separate variables

• The base type of the array is what type the elements in the array are

• Each element has an index, specified by A[i]

• The number of elements is the array length A.length

• The length of an array cannot be changed after it is created

• Accessing an array element out of range generates an exception

Arrays are objects

An array variable can only refer to an array, it does not contain the array.

The value of an array variable can also be null. In that case, it does not refer to any array, and an attempt to refer to an array element such as A[i] will cause a

NullPointerException .

Arrays are created using a special form of the new operator. For example, int[] A = new int[10]; creates a new array with base type int and length 10, and it sets the variable A to refer to the newly created array.

For-each loop (7.1.1)

"for (String name : namelist)" is "for each string, name, in the array, namelist, do the following" for(declaration : expression)

{

//Statements

} it can make the code a little simpler when you want to process all the values in an array in order since it eliminates any need to use array indices.

For-each loops are used to are more compact

Use: for ( String name : namelist ) {

System.out.println( name );

}

Instead of: for (int i = 0; i < namelist.length; i++) {

System.out.println( namelist[i] );

}

For example, if A is an array of type int[] , then we could print all the values from A with the for-each loop: for ( int item : A )

System.out.println( item ); and we could add up all the positive integers in A with: int sum = 0; // This will be the sum of all the positive numbers in A for ( int item : A ) { if (item > 0) sum = sum + item;

}

} public class ForEach1 { public static void main(String[] args) { int[] intarray = { 1,2,3,4}; forDisplay(intarray); foreachDisplay(intarray);

} public static void forDisplay(int[] a){

System.out.println("Display an array using for loop"); for (int i = 0; i < a.length; i++) {

}

System.out.print(a[i] + " ");

}

System.out.println();

} public static void foreachDisplay(int[] data){

System.out.println("Display an array using for each loop");

} for (int a : data) {

System.out.print(a+ " ");

Be careful with the for-each implementation

A for-each loop processes the values in the array, not the elements (where an element means the actual memory location that is part of the array).

For example, consider the following incorrect attempt to fill an array of integers with 17's: int[] intList = new int[10]; for ( int item : intList ) { // INCORRECT! DOES

NOT MODIFY THE ARRAY!

item = 17;

}

7.1.2 Variable Arity Methods

arity of a method is defined as the number of parameters in a call to the method…Why is this useful?

You can pass array into a variable arity method!

public static double average( double... numbers ) {

// Inside this method, numbers if of type double[].

double sum; // The sum of all the actual parameters.

double average; // The average of all the actual parameters.

sum = 0; for (int i = 0; i < numbers.length; i++) {

// Add one of the actual parameters to the sum.

sum = sum + numbers[i];

} average = sum / numbers.length; return average;

}

7.1.3 Array Literals create a new array and fill it with values

Instead of int[] squares = { 1, 4, 9, 16, 25, 36 };

You can use square = new int[] { 1, 4, 9, 16, 25, 36 };

7.2 Array Processing – where computation power is revealed

So far we have:

• Processed elements from beginning to end

• Randomly accessed an arbitrary element

Declare an Array

String [] aArray = new String [ 5 ] ;

String [] bArray = { "a" , "b" , "c" , "d" , "e" } ;

String [] cArray = new

String []{ "a" , "b" , "c" , "d" , "e" } ;

Print an Array in java int [] intArray = { 1 , 2 , 3 , 4 , 5 } ; String intArrayString =

Arrays .

toString ( intArray ) ; // print directly will print reference value System .

out .

println ( intArray ) ; // [I@7150bd4d

System .

out .

println ( intArrayString ) ; // [1, 2, 3, 4, 5]

Create an ArrayList form an array

String [] stringArray = { "a" , "b" , "c" , "d" , "e" } ; ArrayList < String > arrayList = new ArrayList < String > ( Arrays .

asList ( stringArray )) ;

System .

out .

println ( arrayList ) ; // [a, b, c, d, e]

Concatenate two arrays int [] intArray = { 1 , 2 , 3 , 4 , 5 } ; int [] intArray2 = { 6 , 7 , 8 , 9 , 10 } ; // Apache

Commons Lang library int [] combinedIntArray =

ArrayUtils.

addAll ( intArray, intArray2 ) ;

Declare an array inline method ( new String []{ "a" , "b" , "c" , "d" , "e" }) ;

Joins the elements of the provided array into a single string

// containing the provided list of elements

String j = StringUtils.

join ( new String [] { "a" , "b" , "c" } ,

", " ) ; System .

out .

println ( j ) ; // a, b, c

Convert an ArrayList to an array

String [] stringArray = { "a" , "b" , "c" , "d" , "e" } ;

ArrayList < String > arrayList = new

ArrayList < String > ( Arrays .

asList ( stringArray )) ;

String [] stringArr = new String [ arrayList.

size ()] ; arrayList.

toArray ( stringArr ) ; for ( String s : stringArr )

System .

out .

println ( s ) ;

Convert an array to a set

Set < String > set = new

HashSet < String > ( Arrays .

asList ( stringArray )) ;

System .

out .

println ( set ) ;

//[d, e, b, c, a]

Reverse an array int [] intArray = { 1 , 2 , 3 , 4 , 5 } ;

ArrayUtils.

reverse ( intArray ) ;

System .

out .

println ( Arrays .

toString ( intArray )) ;

//[5, 4, 3, 2, 1]

Remove an element of an array (see example on next slide)

String [] stringArray = { "a" , "b" , "c" , "d" , "e" } ;

ArrayList < String > arrayList = new

ArrayList < String > ( Arrays .

asList ( stringArray )) ;

String [] stringArr = new String [ arrayList.

size ()] ; arrayList.

toArray ( stringArr ) ; for ( String s : stringArr )

System .

out .

println ( s ) ;

Convert int to byte array byte [] bytes = ByteBuffer.

allocate ( 4 ) .

putInt ( 8 ) .

array () ; for ( byte t : bytes ) {

System .

out .

format ( "0x%x " , t ) ; }

7.2.1 Some Processing Examples

When an array is full, make a new one and copy the values into it.

if ( playerCt == playerList.length ) {

// The number of players is already equal to the size of the array.

// The array is full. Make a new array that has more space.

Player[] temp; // A variable to point to the new array.

temp = new Player[ 2*playerList.length ]; // Twice as big as the old array.

for ( int i = 0; i < playerList.length; i++ ) { temp[i] = playerList[i]; // Copy item from old array into new array.

} playerList = temp; // playerList now points to the new, bigger array.

}

// At this point, we know that there is room in the array for newPlayer.

playerList[playerCt] = newPlayer; playerCt++;

7.2.2 Some Standard Array Methods

• Arrays.fill( array, value ) -- Fill an entire array with a specified value. The type of value must be compatible with the base type of the array. For example, assuming that numlist is an array of type double[], then Arrays.fill(numlist,17) will set every element of numlist to have the value 17.

• Arrays.fill( array, fromIndex, toIndex, value ) -- Fills part of the array with value, starting at index number fromIndex and ending with index number toIndex-1. Note that toIndex itself is not included.

• Arrays.toString( array ) -- A function that returns a String containing all the values from array, separated by commas and enclosed between square brackets. The values in the array are converted into strings in the same way they would be if they were printed out.

• Arrays.sort( array ) -- Sorts the entire array. To sort an array means to rearrange the values in the array so that they are in increasing order. This method works for arrays of String and arrays of primitive type values (except for boolean, which would be kind of silly). But it does not work for all arrays, since it must be meaningful to compare any two values in the array, to see which is "smaller." We will discuss array-sorting algorithms in Section 7.4.

• Arrays.sort( array, fromIndex, toIndex ) -- Sorts just the elements from array[fromIndex] up to array[toIndex-1]

• Arrays.binarySearch( array, value ) -- Searches for value in the array. The array must already be sorted into increasing order.

This is a function that returns an int. If the value is found in the array, the return value is the index of an element that contains that value. If the value does not occur in the array, the return value is -1. We will discuss the binary search algorithm in

Section 7.4.

7.2.3 RandomStrings Revisited

RandomStringsWithArray.java

.

This program uses parallel arrays. The data for a given copy of the message is spread out across several arrays.

Think of it as: array x in the first column, array y in the second, arraycolor in the third, and array font in the fourth

7.2.4 Dynamic Arrays

• Earlier, we discussed how a partially full array can be used to store a list of players in a game, allowing the list to grow and shrink over the course of the game. The list is

"dynamic" in the sense that its size changes while the program is running. Dynamic lists are very common, and we might think about trying to write a class to represent the concept. By writing a class, we can avoid having to repeat the same code every time we want to use a similar data structure. We want something that is like an array, except that its size can change. Think about operations that we might want to perform on a dynamic array. Some essential and useful operations would include

• add an item to the end of the array

• remove the item at a specified position in the array

• get the value of one of the elements in the array

• set the value of one of the elements in the array

• get the number of items currently in the array

• When we design our class, these operations will become instance methods in that class.

The items in the dynamic array will actually be stored in a normal array, using the partially full array pattern. Using what we know, the class is not difficult to write. We do have to decide what to do when an attempt is made to access an array element that doesn't exist. It seems natural to throw an index-out-of-bounds exception in that case.

Let's suppose that the items in the array will be of type int.

Ok, but this is really a pain….

Suppose that we want to have a dynamic array of String. We can't use a DynamicArrayOfInt object to hold strings, so we need to write a whole new class, DynamicArrayOfString.

we have to write a dynamic array class for every possible type of data!

So, a new array was created to deal with dynamic arrays.

7.3.4 Vectors (old code)

• Don’t use this…

You may see vec.method() in old code.

7.3.1 Array list overview…..

7.3.2 Wrapper Classes

ArrayLists hold objects, but we’ve been using ArrayList with primitives. How can that be?

There is a special class called a Wrapper that holds a primitive type inside an object so that it can be stored in a Arraylist

Primitive Type Wrapper Type int Integer double char boolean

Double

Character

Boolean

7.3.3 Programming With ArrayList

ArrayList

vs.

array

1/2

• construction

String[] names = new String[5];

ArrayList<String> list = new ArrayList<String>();

• storing a value names[0] = "Jessica"; list.add("Jessica");

• retrieving a value

String s = names[0];

String s = list.get(0);

ArrayList

vs.

array

2/2

• doing something to each value that starts with "B" for (int i = 0; i < names.length; i++) { if (names[i].startsWith("B")) { ... }

} for (int i = 0; i < list.size(); i++) { if (list.get(i).startsWith("B")) { ... }

}

• seeing whether the value "Benson" is found for (int i = 0; i < names.length; i++) { if (names[i].equals("Benson")) { ... }

} if (list.contains("Benson")) { ... }

ArrayList "mystery"

• Given:

ArrayList<Integer> list = new ArrayList<Integer>(); for (int i = 1; i <= 10; i++) { list.add(10 * i); // [10, 20, 30, 40, ..., 100]

}

• What is the output of the following code?

for (int i = 0; i < list.size(); i++) { list.remove(i);

}

System.out.println(list);

• Answer:

A. [20, 40, 60, 80, 100]

B. [0, 20, 40, 60, 80]

C. [10, 20, 30, 40, 50]

D. [0, 20, 40, 60, 80]

ArrayList "mystery" 2

ArrayList<Integer> list = new ArrayList<Integer>(); for (int i = 1; i <= 5; i++) { list.add(2 * i); // [2, 4, 6, 8, 10]

}

• What is the output of the following code?

int size = list.size(); for (int i = 0; i < size; i++) { list.add(i, 42); // add 42 at index i

}

System.out.println(list);

• Answer:

A. [42, 42, 42, 42, 42, 2, 4, 6, 8, 10]

B. [42, 6, 8, 10]

C. [2, 4, 6, 8, 10]

D. [2, 4, 6, 8, 10, 42, 42, 42, 42, 42]

Objects storing collections

• An object can have an array, list, or other collection as a field.

public class Course { private double[] grades; private ArrayList<String> studentNames; public Course() { grades = new double[4]; studentNames = new ArrayList<String>();

...

}

• Now each object stores a collection of data inside it.

ArrayList

as parameter

public static void name ( ArrayList< Type > name ) {

• Example:

// Removes all plural words from the given list.

public static void removePlural( ArrayList<String> list ) { for (int i = 0; i < list.size(); i++) {

String str = list.get(i); if (str.endsWith("s")) { list.remove(i); i--;

}

}

}

• You can also return a list: public static ArrayList< Type > methodName ( params )

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

String item = namelist.get(i);

System.out.println(item);

}

Is the same as for ( String item : namelist ) {

System.out.println(item);

}

Beware issues with unboxing and null values

double sum = 0; for ( double num : numbers ) { sum = sum + num;

}

Modified to check for null values double sum; for ( Double num : numbers ) { if ( num != null ) { sum = sum + num; // Here, num is SAFELY unboxed to get a double.

}

}

} import java.util.ArrayList;

/**

* Reads a list of non-zero numbers from the user, then prints

* out the input numbers in the reverse of the order in which

* the were entered. There is no limit on the number of inputs.

*/ public class ReverseWithArrayList { public static void main(String[] args) {

ArrayList<Integer> list; list = new ArrayList<Integer>();

System.out.println("Enter some non-zero integers. Enter 0 to end."); while (true) {

System.out.print("? "); int number = TextIO.getlnInt(); if (number == 0) break; list.add(number);

}

}

System.out.println();

System.out.println("Your numbers in reverse are:"); for (int i = list.size() - 1; i >= 0; i--) {

System.out.printf("%10d%n", list.get(i));

}

Simple example with variable length text input

import java.util.Collections; import java.util.ArrayList; public class Program { public static void main(String[] args) {

ArrayList<String> list = new ArrayList<>(); list.add("cat"); list.add("bird"); list.add("ant"); list.add("dog");

And now we can sort!

Collections.sort(list);

} for (String value : list) {

System.out.println(value);

// Sort the elements alphabetically.

}

}

static void insertionSort(int[] A) {

// Sort the array A into increasing order.

int itemsSorted; // Number of items that have been sorted so far.

for (itemsSorted = 1; itemsSorted < A.length; itemsSorted++) {

// Assume that items A[0], A[1], ... A[itemsSorted-1]

// have already been sorted. Insert A[itemsSorted]

// into the sorted part of the list.

int temp = A[itemsSorted]; // The item to be inserted.

int loc = itemsSorted - 1; // Start at end of list.

} while (loc >= 0 && A[loc] > temp) {

A[loc + 1] = A[loc]; // Bump item from A[loc] up to loc+1.

loc = loc - 1; // Go on to next location.

}

}

A[loc + 1] = temp; // Put temp in last vacated space.

static void selectionSort(int[] A) {

// Sort A into increasing order, using selection sort for (int lastPlace = A.length-1; lastPlace > 0; lastPlace--) {

// Find the largest item among A[0], A[1], ...,

// A[lastPlace], and move it into position lastPlace

// by swapping it with the number that is currently

// in position lastPlace int maxLoc = 0; // Location of largest item seen so far.

for (int j = 1; j <= lastPlace; j++) { if (A[j] > A[maxLoc]) {

// Since A[j] is bigger than the maximum we've seen

// so far, j is the new location of the maximum value

// we've seen so far.

maxLoc = j;

}

}

} int temp = A[maxLoc]; // Swap largest item with A[lastPlace].

A[maxLoc] = A[lastPlace];

A[lastPlace] = temp;

} // end of for loop

7.5.1 The Truth About 2D Arrays

7.5.2 Conway's Game Of Life

Life.java

MosaicPanel.java

7.5.3 Checkers

Download