DOC PREVIEW
UW-Madison COMPSCI 302 - Arrays Study Notes

This preview shows page 1 out of 2 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 2 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 2 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Arrayshandout for CS 302 by Will Benton (willb@cs)arrays.graffle: Created on Tue Jul 18 2006; modified on Wed Jul 19 2006; page 1 of 2Copyright © 2006 Will C. BentonAn array is a sequence of places to hold values of the same type. The length of an array may be decided at run-time or compile-time, but once an array is created, its size is fixed.Declaring an arrayint[] scores;You can store references to arrays in variables, in object or class fields, and in elements of other arrays. The type of a variable holding an array is given by basetype [], where basetype is the type of values stored in the array in question; pronounce x[] as "array of x"For example, the following line of code declares a variable called scores. scores holds a reference to an array of int values. This code does not actually create an array, just as declaring a variable with an object reference type does not actually create an object.The following line of code declares a variable names that holds a reference to an array of String references.String[] names;Creating an arrayJust as you create instances of classes with operator new, you can create arrays with operator new:names = new String[4];The preceding line of code creates a new array containing places for four String references, and gives names a reference to the newly-created array. Of course, you may combine declaration and initialization as always.(Note that no actual String instances are created by the preceding code snippet.)Inspecting array metadataSince the size of an array is not part of its type (that is, an int[] may have five elements, five million elements, or no elements at all), you will often want to determine at run-time how many elements are in an array, so that your program only accesses a particular array using valid element numbers.Every array supports the length field. This field indicates the number of elements in the array. length is instance-final: its value is fixed at array creation.int x = names.length;System.out.println(x + " names");Accessing array elementsYou may access the elements of an array with the subscript operator (also known as the index operator). To access an array a at index i, simply write the following: a[i]The following line of code gives the reference in the first element of names to a String called firstName. (Note that the first element of an array has index number 0!) After this line of code executes, names[0] and firstName will refer to the same object.String firstName = names[0];Updating array elementsAn array access expression involving the subscript operator (that is, one of the form a[i]) may appear as a value (as above) or on the left-hand side of an assignment. To give a value to an array element, simply write an assignment statement that gives a value to an array access expression.For example, the following line of code gives the value 42 to the third element (i.e. that with index 2) of scores.scores[2] = 42;String[] names = new String[5];Some example memory diagramsnamesNote that all elements of names are currently null. Every element of a newly-allocated array has the default value for its type.names[2] = "fred";namesString"fred"String fred = names[2];namesString"fred"frednames[names.length - 1] = "wilma";namesString"fred"fredString"wilma"arrays.graffle: Created on Tue Jul 18 2006; modified on Wed Jul 19 2006; page 2 of 2 Copyright © 2006 Will C. BentonIterating over an arrayfor (int i = 0; i < scores.length; i++) { scores[i] = GradeUtil.curve(scores[i]);}Often, you will want to access or modify every element of an array. The most common idiom for this uses a for loop, as in the heartening example below:Copying array contentsint[] newScores = new int[scores.length];for (int i = 0; i < scores.length; i++) { newScores[i] = scores[i];}To copy the contents of one array to another, simply use iterate through the array to be copied from and give each value to the corresponding element in the array to be copied to.Note that the last valid index of some array a is given by (a.length - 1). This is the case because array indices are numbered starting with 0.The preceding code snippet creates a new array called newScores and copies each element from scores into newScores.Advanced (i.e. "post-302") programmers may use the System.arraycopy method:int[] newScores2 = new int[scores.length];System.arraycopy(scores, 0, newScores2, 0, scores.length);Check the Java API documentation for more on System.arraycopy.Extremely advanced (i.e. "lazy") programmers may use the clone method, but only if they understand what it does!int[] newScores3 = (int[])scores.clone();Literal arraysint[] fiveFibs = {1, 1, 2, 3, 5};It is occasionally convenient to specify a literal array. Your programs will use these analogously to String or int literals. A literal array is a comma-separated list of elements surrounded by curly braces:Note that the size of the fiveFibs array is implicit. Unlike String and primitive literals, you can only use the above syntax as the initializer in a variable declaration. (Of course, you can use a String literal any place that a reference to a String is expected -- and you can use a primitive literal in any place where a value of the same type is appropriate.) If you'd like to use a literal array in any place where an array reference is expected (e.g. on the right-hands of assignments, as arguments to methods, etc.) you'll have to use the following alternate syntax:fiveFibs = new int[] {1, 1, 2, 3, 5};Util.printArray(new int[] {1, 2, 3});It's funny-looking, but it works. (The Util class and printArray method don't really exist, but you could certainly devise your own.)Out of space?int newLength = scores.length * 2 + 1;int[] newScores = new int[newLength];for (int i = 0; i < scores.length; i++) { newScores[i] = scores[i];}Since arrays are fixed-size, you may find that an array isn't large enough for the sequence of values you wish to store in it. In this case, you will need to allocate a new, larger array and copy the values from the old array.In general, a good size for the new array is 2x + 1, where x is the size of the old array. Resizing in this way provides a good tradeoff between saving space and saving time.Multiple dimensions: arrays of arraysWhile Java does not directly support multidimensional arrays in the way that some other languages do, it is straightforward enough to simulate multidimensional arrays by declaring an array of arrays.int[][] twoDee = new


View Full Document

UW-Madison COMPSCI 302 - Arrays Study Notes

Download Arrays Study Notes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Arrays Study Notes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Arrays Study Notes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?