Array1

14
Introduction to Data Structures

Transcript of Array1

Introduction to Data Structures

Arrays

An array is an indexed set of variables, such as

dancer[1], dancer[2], dancer[3],… It is like a set of

boxes that hold things.

A list is a set of items.

An array is a set of

variables that each

store an item.

Arrays and Lists

You can see the difference between arrays and

lists when you delete items.

Arrays and Lists

In a list, the missing spot is filled in when

something is deleted.

Arrays and Lists

In an array, an empty variable is left behind

when something is deleted.

Arrays

Arrays can be created in a similar manner, but

more often they are created using the array

visualization object from the Alice local gallery.

The Array Visualization object

has special properties and

methods for manipulating

the elements in an array.

Arrays

Alice has a set of built-in functions that can be

performed on arrays.

Introducing ArraysArray is a data structure that represents a collection of the same types of data.

myList[0]

myList[1]

myList[2]

myList[3]

myList[4]

myList[5]

myList[6]

myList[7]

myList[8]

myList[9]

double[] myList = new double[10];

myList reference

An Array of 10 Elementsof type double

Declaring Array Variables• datatype[] arrayname;

Example:

double[] myList;

• datatype arrayname[];

Example:

double myList[];

Creating Arrays

arrayName = new datatype[arraySize];

Example:myList = new double[10];

myList[0] references the first element in the array.

myList[9] references the last element in the array.

Declaring and Creatingin One Step

• datatype[] arrayname = new

datatype[arraySize];

double[] myList = new double[10];

• datatype arrayname[] = new datatype[arraySize];

double myList[] = new double[10];

The Length of Arrays

• Once an array is created, its size is fixed. It cannot be changed. You can find its size using

arrayVariable.length

For example,myList.length returns 10

Initializing Arrays

• Using a loop:

for (int i = 0; i < myList.length; i++)

myList[i] = i;

• Declaring, creating, initializing in one step:

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

This shorthand syntax must be in one statement.

Declaring, creating, initializing Using the Shorthand Notation

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

This shorthand notation is equivalent to the following statements:

double[] myList = new double[4];

myList[0] = 1.9;

myList[1] = 2.9;

myList[2] = 3.4;

myList[3] = 3.5;