Grouping Data Together Often we want to group together a number of values or objects to be treated...

21
Grouping Data Together Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial group exam marks for students in a subject items in a catalogue orders for gifts We need a better technique than creating a variable for each value or object.

description

Logical View of an Array An array is like a street with houses that can hold things. The houses are numbered so that they can be accessed. In some languages (including Java), the first house number is zero. In other languages, the numbering starts from 1. The number of houses is fixed when the array is created, and cannot be changed without recompiling the program

Transcript of Grouping Data Together Often we want to group together a number of values or objects to be treated...

Page 1: Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.

Grouping Data TogetherGrouping Data Together

• Often we want to group together a number of values or objects to be treated in the same way e.g. • names of students in a tutorial

group• exam marks for students in a

subject• items in a catalogue• orders for gifts

• We need a better technique than creating a variable for each value or object.

Page 2: Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.

Arrays

• An array in Java is a collection of values of the same type .

• The elements in an array are held in contiguous memory locations.

• The array class is special. It has a small number of predefined methods, and a special notation of its own to invoke them.

Page 3: Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.

Logical View of an ArrayLogical View of an Array

An array is like a street with houses that can hold things.

The houses are numbered so that they can be accessed. In some languages (including Java), the first house number is zero. In other languages, the numbering starts from 1.

The number of houses is fixed when the array is created, and cannot be changed without recompiling the program.

0 1 2 3 4 5 6 7 8 9 10

Page 4: Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.

Declaring & Initializing an Array• One way to create an array with some

values in it is to initialize it when it is created. In this case, the compiler will make the array as big as it needs to be to hold the values specified.

• int[] marks = {10, 45, 67, 88, 50};

marks

10

4567

88

50

Page 5: Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.

5

Examples of Declaring Arrays float[] prices = new float[500];

int[] marks = {10, 45, 67, 88, 50};

boolean[] flags; flags = new boolean[20];

char[] codes = new char[1750]; char[] letterGrades = {'A', 'B', 'C', 'D', 'F'};

Page 6: Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.

6

Array Declarations Revisited

• The brackets of the array type can be associated with the element type or with the name of the array

• Therefore the following declarations are equivalent:

float[] prices; float prices[];

• The first format is generally more readable

Page 7: Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.

Command-Line Arguments• The signature of the main method indicates that it takes an

array of String objects as a parameter• These values come from command-line arguments that are

provided when the interpreter is invoked• For example, the following invocation of the interpreter

passes an array of three String objects into main:

> java DoIt pennsylvania texas california

• These strings are stored at indexes 0-2 of the parameter• See NameTag.java (page 281)

Page 8: Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.

Memory Allocation for Memory Allocation for ArrayArray

10001004

1008

1012

1016

marks[0]

marks[1]

marks[2]

marks[3]

marks[4]

Array accessMemory mapAddress

10

45

67

88

50marks

1000

Page 9: Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.

Accessing an ArrayAccessing an Array

An element is accessed by specifying its position in the array:arrayName[index]

whereindex is a value (of type int) used to

select a particular element in the array.

The lowest valid index is zero, and the highest is

(size of the array) - 1.

Page 10: Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.

Evaluating an Index• Any expression that evaluates to an int can be

used as an index (also called a subscript).• Given the following definitions:int subscript = 0; int[] marks = new int[10];

• we could access elements by expressions such as:marks[0]marks[subscript + 2] marks[10-1]

• An index that is outside the array will cause an ArrayIndexOutOfBoundsException error message.

Page 11: Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.

Assigning Values to an Assigning Values to an ArrayArray

You can assign values to particular array elements.

int counter = 1;

marks[4] = 18;marks[0] = 56;marks[counter] = 38;marks[counter + 1] = 87;

Page 12: Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.

Extracting Values from an Array

• A value extracted from an array can be treated like any other value, e.g. (assuming that the relevant declarations and initializations have been done)

• System.out.println(marks[1]);

• total += marks[counter];

• aStudent.calculateTotalMark(marks[counter]);

Page 13: Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.

Displaying the Contents of the Array

public void printArray(){ int[] marks = {10, 45, 67, 88, 0, 66}; System.out.println(); int counter = 0; while (counter < marks.length){ System.out.println(marks[counter]);counter++;

}}

Page 14: Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.

Another Way of Displaying the Array

public void printArray(){ int[] marks = {10, 45, 67, 88, 50}; System.out.println(); for (int counter = 0;

counter < marks.length; counter++) System.out.println(marks[counter]);

}

marks.length returns the number of elements in the marks array. Note that this is not a method call. Do not confuse this with the String class's length() method.

Page 15: Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.

Creating an Array of floats• As with any object, the name of an array

is a reference to the array itself. To put aside some memory, we need to use the new operator.

double[] prices = new double[6];

prices

Page 16: Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.

Creating an Array of Objects• An array of objects is actually an array

of references to objects. Person[] family = new Person[6];

family

These references havenot been initialized. Theyhave NULL values. We have not yet created the Person objects themselves.

Page 17: Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.

An Array of Objects• For each element of the array, we need

to create an object that it references.

family

Page 18: Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.

Creating the Objects for the Array

public static void main(String [] Args){ Person[] family = new Person[6]; for (int counter = 0; counter < family.length;

counter++) family[counter] = new Person();

for (int counter = 0; counter < family.length; counter++) { System.out.println("Name?"); family[counter].setName(Keyboard.readString());

}

…}

Page 19: Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.

Passing Arrays as Passing Arrays as ArgumentsArguments

When passing an entire array to a method, the name of the array is passed without any brackets. The name of an array is a reference to the array.

Brackets in the formal parameter show it is an array, without specifying its size. The array knows how big it is.

Because a method is passed a reference to the array, a change to its contents in the called method will change it in the calling method.

Page 20: Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.

Arrays as ParametersArrays as Parameters public void passArray(){ String[] food = {"apple", "fig", "banana", "orange"};

System.out.println(countShortWords(food));}

private int countShortWords(String[] words){ int shortWords = 0;

for (int counter = 0; counter < words.length; counter++)

if (words[counter].length() < 4) shortWords++;

return shortWords;}

... contd.

Page 21: Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.

Changing the Contents of an Array in a Called Method

public void changePassedArray(){ String[] food = {"apple", "fig", "banana", "orange"}; changeShortWords(food); displayStringArray(food);

}

private void changeShortWords(String[] words){ for (int counter = 0; counter < words.length;

counter++) if (words[counter].length() < 4) words[counter] =

words[counter].toUpperCase();}