array elements - computing science - simon fraser …tamaras/arrays/arrays_4up.pdf ·...
TRANSCRIPT
CMPT 126: Lecture 6
Arrays
Tamara Smyth, [email protected]
School of Computing Science,
Simon Fraser University
September 25, 2007
1
Array Elements
• An array is a construct used to group and organizedata.
• By using an array, we don’t have to declare separatevariables for large amounts of data.
• An array is a list of values of the same type, each onestored at a specific numbered position called an index.
array elements
5
4
3
2
1
0
indeces
88
78
32
42
67
4
Figure 1: An array.
• An array of size N is indexed from 0 to N − 1.
CMPT 126: Arrays, Lecture 6 2
Declaring and Using Arrays
• In Java, an array is an object that must beinstantiated. To create an array, the reference to thearray must be declared:
int[] height = new int[11];
where the variable is height, which is declared to bean array of eleven integers.
• The instantiation of height, using the new operator,reserves the memory space to store 11 integers.
• The size of an array cannot be changed.
• To access a value in an array, we use the name of thearray followed by the index in square brackets:
height[2] = 45;
CMPT 126: Arrays, Lecture 6 3
Initializer list
• The array may also be initialized at declaration usingan initializer list, in which case the new operator isnot used:
int[] height = {2, 34, 45, 22, 235};
• An initializer list can only be used when an array isfirst declared.
• The type of each value in the initializer list mustmatch the array element type.
CMPT 126: Arrays, Lecture 6 4
PrintArray.java
• It is often convenient to use for loops when handlingarrays because the number of positions in the array isconstant.
public class PrintArray
{
public static void main(String[] args)
{
final int LIMIT = 15, MULTIPLE = 10;
int[] list = new int[LIMIT];
// initialize the array values
for (int i = 0; i< LIMIT; i++)
list[i] = i * MULTIPLE;
list[5] = 999; //change one value
// Print the array values
for (int value : list)
System.out.print(value + " ");
}
}
• Every Java array is an iterator so the version of forthat extracts each value in the specified iterator maybe used.
CMPT 126: Arrays, Lecture 6 5
Bounds Checking
• Bounds checking ensures that an index used to referto an array element is in range.
• The index operator performs automatic bounds
checking, though we will still want to perform ourown bounds checking.
• A reference to an array must be greater than orequal to zero, and less than the size of thearray.
• The length of the array may be determined using itslength constant.
public class PrintArray
{
public static void main(String[] args)
{
int[] list = {12, 2, 8, 234, 11};
// initialize the array values
for (int i = 0; i<list.length; i++)
System.out.print(list[i] + " ");
}
}
CMPT 126: Arrays, Lecture 6 6
Alternate Array Syntax
• There are two ways to declare an array reference inJava.
1. associate the brackets with the type of valuesstored:
int[] grades;
2. associate the brackets with the name of the array.
int grades[];
• The first is consistent with other types of declarations.
CMPT 126: Arrays, Lecture 6 7
Arrays as Parameters
• An entire array can be passed as a parameter to amethod.
• What is actually passed is a copy of the reference tothe original array.
• This implies that a method that receives an array as aparameter can permanently change an element of thearray.
CMPT 126: Arrays, Lecture 6 8
Arrays of Objects
• Arrays can also be used to store objects as elements,often facilitating the management of more complexstructures.
– an array could contain objects that consist ofseveral variables (which may themselves be otherarrays) and methods.
• Instantiating an array of objects allocates memory tostore references only. The objects that are storedin each element must be instantiatedseparately.
CMPT 126: Arrays, Lecture 6 9
Instantiating an Array of Objects
• The new operator creates an array, and reserves thememory, in this example, for 5 String references. Itdoes not create any String objects.
String[] authors = new String[5]
authors
Figure 2: authors: an array of string references.
CMPT 126: Arrays, Lecture 6 10
Instantiating Array Objects (Strings)
• Recall that String objects may be represented asstring literals, allowing the following declarations:
String[] authors = {"Kurt Vonnegut",
"Douglas Coupland",
"Paul Auster",
"Salmon Rushdie",
"Julian Barnes"};
"Douglas Coupland"
"Paul Auster"
"Kurt Vonnegut"
"Salmon Rushdie"
"Julian Barnes"
authors
Figure 3: authors: an array of string references to instantiated string objects.
CMPT 126: Arrays, Lecture 6 11
Command-line Arguments
• Recall from lab 1 that command-line arguments arestored in an array of String objects and are passedto the main method.
public class NameTag
{
public static void main(String[] args)
{
System.out.println();
System.out.println(" " + args[0]);
System.out.println("My name is " + args[1]);
}
}
• Any information on the command line beyond theprogram name is stored in args when the interpreteris invoked, and may be used to provide input into theprogram.
>> java NameTag Greetings! Tamara
Greetings!
My name is Tamara
• If two strings are not provided on the command line,an ArrayIndexOutOfBoundsException will bethrown.
CMPT 126: Arrays, Lecture 6 12
Variable Length Parameters Lists
• Java provides a way to define methods that acceptvariable length parameter lists.
public class MyAverage
{
static double average(int ... list) {
double result = 0.0;
if (list.length !=0) {
int sum = 0;
for (int num : list)
sum += num;
result = (double)sum/list.length;
}
return result;
}
public static void main(String[] args) {
double avg1 = average(1, 23, 43);
double avg2 = average(23, 34, 44, 56, 2, 34, 9, 3);
System.out.println(avg1);
System.out.println(avg2);
}
}
Output:
22.333333333333332
25.625
CMPT 126: Arrays, Lecture 6 13
• The parameters are automatically put into an arrayfor easy processing in the method.
• A method cannot accept two sets of varyingparameters, but can accept other parameters.
CMPT 126: Arrays, Lecture 6 14
Two-Dimensional Arrays
• Two dimensional arrays have values in twodimensions, which you may think of as rows andcolumns.
• Brackets are used to represent each dimension in thearray: a 2-D array storing integers is int[][].
two dimensionone dimension
Figure 4: A one and two dimensional array.
• In reality, a 2-D array is an array of arrays, and isreally a 1-D array of references to arrays.
CMPT 126: Arrays, Lecture 6 15
Multidimensional Array
• Though it’s a little harder to visualize, arrays canhave one, two, three, or more dimensions.
• This is easier to comprehend when you understandhow multidimensional arrays are implemented, andconsider each array as having a reference that is partof another array.
• Alternatively (and equivalently), think of onedimension as being a subdivision of the previous one.
• Java does not directly support multidimensionalarrays. Rather they must be implemented by theprogrammer as array of references to array object.
• In some cases you may find it difficult to mange datain this was, and opt to use objects instead.
CMPT 126: Arrays, Lecture 6 16
The ArrayList Class
• An ArrayList is similar to an array, but it changesits size dynamically, as needed.
CODE:
ArrayList band = new ArrayList();
band.add(‘‘Paul’’);
band.add(‘‘Pete’’);
band.add(‘‘John’’);
band.add(‘‘George’’);
System.out.println(band);
OUTPUT:
[Paul, Pete, John, George]
• To access an element at a particular index, use theobject’s get method:
System.out.println(‘‘At index 1: ’’ + band.get(1));
OUTPUT:
Pete
CMPT 126: Arrays, Lecture 6 17
ArrayList is Dynamic
• Since ArrayList is dynamic, elements may beinserted and removed from any location.
CODE:
int index = band.indexOf(‘‘Pete’’);
band.remove(index);
System.out.println(band);
OUTPUT:
[Paul, John, George]
• When an element is deleted, the ArrayList
“collapses” so that indeces are still incremental forthe remaining elements.
• To add at a particular index, use the object’s addmethod but with two parameters: the index andthe object to be added.
CODE:
band.add(2, ‘‘Ringo’’);
System.out.println(band);
OUTPUT:
[Paul, John, Ringo, George]
CMPT 126: Arrays, Lecture 6 18
ArrayList Element Type
• An ArrayList typically stores a list of references tothe Object class, rather than a more specific datatype, allowing storage of various data types in onearray.
CODE:
ArrayList myarray = new ArrayList();
myarray.add(2);
myarray.add(‘‘string’’);
System.out.println(myarray);
OUTPUT:
[2, string]
• Primitive data types are promoted to theircorresponding wrapper class.
CMPT 126: Arrays, Lecture 6 19
Caveat with Unspecified Types
• To remove an object (which is of type Object), itmust be cast to its original class.
• For example, the following will not compile as it seesthe reference to the Object class (obtained using theget method) as being incompatible with the integer2:
System.out.println(myarray.get(0) + 2)
• Rather, the reference to the Object class must becast to a reference of type Integer (its original type)or some other compatible type:
System.out.println((Integer)myarray.get(0) + 2)
CMPT 126: Arrays, Lecture 6 20
Specifying an Element Type forArrayList
• An ArrayList is a generic type, meaning we canspecify a specific element type:
ArrayList<Family> reunion = new ArrayList<Family>();
• Declaring the element type is usually a good ideabecause it adds a level of type checking, andeliminates the need to cast when extracting objects.
ArrayList<Integer> myarray = new ArrayList<Integer>();
myarray.add(2);
System.out.println(myarray.get(0) + 2);
CMPT 126: Arrays, Lecture 6 21
ArrayList Efficiency/Implementation
• When an element is inserted into an ArrayList, allof the elements at higher indexes are copied into theirnew locations to make room for the next element.
8
34 2 4 6 87 5 56
Figure 5: Inserting an element into an ArrayList.
• A Similar process occurs when an element is removed.If several elements are inserted or deleted, thiscopying is repeated many times, which can makeprocessing inefficient.
• Collections classes will be discussed later in thecourse.
CMPT 126: Arrays, Lecture 6 22
Polygons and Polylines
• Arrays are helpful when drawing complex shapes.
• A polygon is a multisided shape defined in Java usinga series of (x,y) points that indicate the vertices ofthe polygon.
• Arrays are often used to store the list of coordinates.
• The methods used to draw a polygon are calleddrawPolygon and fillPolygon. These areoverloaded.
• One version using arrays, these methods take threeparameters. The first two parameters are arrays ofintegers representing the x and y coordinates, and thethird is an integer that indicates how many points areused from each of the two arrays.
• A polyline is similar to a polygon, but is not a closed
shape.
CMPT 126: Arrays, Lecture 6 23
Rocket.java
public class RocketPanel extends JPanel
{
private int[] xRocket = {100, 120, 120, 130, 130, 70, 70, 80, 80};
private int[] yRocket = {15, 40, 115, 125, 150, 150, 125, 115, 40};
public RocketPanel()
{
setBackground(Color.black);
setPreferredSize(new Dimension(200, 200));
}
public void paintComponent(Graphics page)
{
super.paintComponent(page);
page.setColor(Color.cyan);
page.fillPolygon(xRocket, yRocket, xRocket.length);
}
}
Figure 6: Java Rocket output.
CMPT 126: Arrays, Lecture 6 24
CMPT 126: Arrays, Lecture 6 25