Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

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 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.

2 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.

3 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. 012345678910

4 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 45 67 88 50

5 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'};

6 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

7 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) NameTag.java

8 Memory Allocation for Array 1000 1004 1008 1012 1016 marks[0] marks[1] marks[2] marks[3] marks[4] Array accessMemory mapAddress 10 45 67 88 50 marks 1000

9 Accessing an Array An element is accessed by specifying its position in the array: arrayName[index] where index 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.

10 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.

11 Assigning Values to an Array You can assign values to particular array elements. int counter = 1; marks[4] = 18; marks[0] = 56; marks[counter] = 38; marks[counter + 1] = 87;

12 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[count er]);

13 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++; }

14 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.

15 Creating an Array of float s 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

16 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 have not been initialized. They have NULL values. We have not yet created the Person objects themselves.

17 An Array of Objects For each element of the array, we need to create an object that it references. family

18 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()); } … }

19 Passing Arrays as Arguments  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.

20 Arrays 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.

21 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(); }


Download ppt "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."

Similar presentations


Ads by Google