0% found this document useful (0 votes)
10 views

Arrays 1D, 2D

An array is a collection of elements of the same type stored in contiguous memory locations. An array knows its own size through its length property. There are three steps to create an array: 1) declare an array reference variable, 2) create the array object and allocate memory using the new keyword, specifying the size, and 3) assign values to the elements of the array using indexes. Arrays can be passed as parameters to methods and used to efficiently process large datasets.

Uploaded by

ankur.gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Arrays 1D, 2D

An array is a collection of elements of the same type stored in contiguous memory locations. An array knows its own size through its length property. There are three steps to create an array: 1) declare an array reference variable, 2) create the array object and allocate memory using the new keyword, specifying the size, and 3) assign values to the elements of the array using indexes. Arrays can be passed as parameters to methods and used to efficiently process large datasets.

Uploaded by

ankur.gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 50

Arrays

James Brucker
Arrays
An array is a series of elements of the same type, which
occupy consecutive memory locations.
float[] x = new float[10]; // array of 10 float vars
char[] c = new char[40]; // array of 40 char vars

Array x[] in memory:


x[0] x[1] x[2] . . . x[9]

4 Bytes = size of float


Array c[] = new char[40] in memory :
c[0] c[1] . . . c[39]

2 Bytes = size of char


Array is an Object
In C, C++, Fortran, etc., an array is just a collection of
sequential memory locations (as in previous slide).

x[0] x[1] x[2] . . . x[9]

In Java and C#, an array is an object.


This means an array can have methods and attributes,
such as the length of the array
Array x[] in Java is an object: it encapsulates data.
Array<float>
x is an array reference
length=10
x data is in an array object
float[0]=. . .
float[1]=. . .
Structure of an array
The first element has index 0.
An array has a fixed length (size cannot be changed).
float[] x = new float[10];
x[0] = 20;
x[1] = 0.5F;
x float[ ] (array)
length=10 array
[0]=20.0 object in
[1]= 0.5 memory
[2]= 0.0
...
[9]= 0.0
Array knows its own size!
Every array has an attribute named length
double[] x = new double[20];
x.length // returns 20
x.length is 20.
The first element is x[0],
the last element is x[x.length -1].

Don't forget -1 !

In Java, an array is an object.


length is a property (attribute) of the array object.
Why Use Arrays?

Make it easy to process lots of data using loops.

Perform operations on vectors and matrices.

Examples are given in later slides.


3 Steps to create an array
There are 3 steps to define & initialize an array.
Memorize them! A common programming error is to
omit one of these steps.
1. Define array String[ ] colors;
variable (reference) double[ ] x;

2. Create the array x=


& specify its size. new double[10]; colors =
new String[3];

3. Assign values to x[0] = 10.0; colors[0] = "red";


array elements. x[1] = 0.5; colors[1] = "blue";
... colors[2] = "green";
1. Define array reference
Declare p as type "array of int".
OK to omit space after "int" and between [ ].
<<memory>>
int [] p; p null

This creates an array reference p,


but does not create an array.

p does not refer to anything yet!


Just like:
String s;
defines a String reference but
does not create a string.
2. Create the Array object
Create the array using "new".
array = new DataType[ size ]
<<memory>>
p = new int[10]; p <object>

new object Array Storage in memory:

"new" creates a new object. int[]


01000 length=10
Here, it creates an array 01004
containing 10 "int" values. 01008
It sets p to refer to this object. 0100C 10 int's
01010
01014
....
3. Initialize elements of the array
When you create the array, Java does not initialize the
array elements. You must do this.
<<memory>>
for(int k=0; k < 10; k++) p <object>
p[k] = k;
Array storage in memory:

int[]
length=10
You can initialize array elements 0
any way you like. 1
2
Some examples in later slides. ...
Short-cut to create an Array
You can combine steps (1) and (2) into one statement:
<<memory>>
int[] p = new int[10]; p <object>

This statement does two things:


int[]
length=10
1) define p as an array reference 0
2) create an array with 10 0
0
elements and assign it to p ...
Another short-cut
If you have fixed values to put in the array, you can
combine steps 1 - 3 into one statement:
int[] p = { 2, 4, 6, 8, 10};
p <object>

This statement does 3 things:


int[]
length=5
1) define p as an array reference 2
2) create array with 5 int's 4
6
3) stores values 2, 4, ... 10 in the 8
array 10
Summary: steps to create array
1. Define an array reference:
double [] x;

2. Create the array (allocate storage for elements) :


x = new double[10];

3. Assign values to the array elements:


for(int k=0; k<x.length; k++) x[k] = 2*k;

Short-cut: define array reference and create object


double[] x = new double[10];
Meaning of [] in "String[] x"
The [ ] means "array of ..." or "... array".

int[] means "int array" or "array of int".

Foo[] means "Foo array" or "array of Foo".

int[ ] x; x is type "int array"


main(String[] args) args is type "String array"
char[] c = {'c','a','t'} c is type "char array"
double[] getScores() getScores returns
"array of double"
Error: invalid array index
The elements of an array a have indices from 0 to
a.length - 1.
If a program tries to access an array using an invalid
index, then Java throws an
ArrayIndexOutOfBoundsException.

double [ ] a = new double[10];


a[10] = 1.0;

Exception in thread "main"


java.lang.ArrayIndexOutOfBoundsException: 10
at MyProgram.badAccess(MyProgram.java:82)
at MyProgram.main(MyProgram.java:68)
Inspect an array using BlueJ

Demo in class.

Use BlueJ to see inside an array


(called inspection)
Read Data into an Array
Suppose we want to read some words from the input into an
array. Maybe we know that the input will never contain more
than 100 words. We could write...

// create Scanner to read input


Scanner input = new Scanner( System.in );
// create array of words (Strings)
String [ ] words = new String[100];
// read the data
int count = 0;
while(input.hasNext() && count < words.length)
{ words[count] = input.next( );
count++;
}
// now count = number of words actually read
Sort Data in an Array
java.util.Arrays - provides static methods for arrays.
One method is: Arrays.sort( array[] )

/** Sort the words[ ] array from last slide */


/** You must "import java.util.Arrays". */

Arrays.sort( words );

Input data Result:


dog words[0] = "ANT"
cat Arrays.sort( ) words[1] = "DOGS"
frog words[2] = "cat"
DOGS words[3] = "dog"
ANT words[4] = "frog"
Sort part of an Array
The previous slide is not quite correct.
Since we only have data for part of the array, we
should sort only that part. Use:
Arrays.sort(array[ ], start_index, end_index)

// sort elements 0 until count (exclusive)


Arrays.sort( words, 0, count );

This sorts only the elements


words[0] words[1] ... words[count-1]
Output the Elements of an Array
Now lets print the values of the array.
// write a loop to display each array element

for( int k=0; k < count ; k++ )


System.out.printf("%d: %s\n", k, words[k]);

Output:
0: ANT
1: DOGS
2: cat
3: dog
4: frog
An Array of Fibonacci Numbers
This example shows how to process all elements of an array.
The important point is that the "for" loop starts at k=0 and tests
k < fib.length (false when k=fib.length)

final int ARRAYSIZE = 20; // a constant value


long [ ] fib = new long[ ARRAYSIZE ];
fib[0] = fib[1] = 1;
for(int k = 2; k < fib.length; k++ )
fib[k] = fib[k-1] + fib[k-2];

// output the values


for(int k = 0; k < fib.length; k++ )
System.out.printf("f[%d] = %d\n",k, fib[k]);
Array as parameter
Use the same syntax as declaring an array variable.
/** Print the array elements. */
public void printArray( String[] array ) {
for(int k=0; k< array.length; k++)
System.out.printf("[%d] = %s\n",
k, array[k] );

/** Return maximum element in array. */


public double max( double[] array ) {
double max = array[0];
for(int k=1; k<array.length; k++) {
if (array[k] > max) max = array[k];
return max;
}
main has String array parameter
The main method accepts array of Strings.
/** args = command line arguments */
public static void main( String[] args ) {
for(int k=0; k < args.length; k++)
System.out.printf("args[%d] = %s\n",
k, args[k] );

The parameters to main are strings given on command line


when running the class in the JVM.
For example:
cmd> java MyClass hi there
args[0] = "hi"
args[1] = "there"
Method can return an array
A method can return an array:
/** Create an array and fill it with "1" */
static double[] makeOnes(int size) {
double x = new double[size];
// use Arrays.fill() is better
for(int k=0; k<size; k++) x[k] = 1.0;
return x;
}
Avoid this Common Mistake!
What does "b = a" do?
What will be printed?
int [] a = { 2, 4, 6, 8 };
int [] b = { 0, 0, 0 };
b = a; // What does this do?
b[2] = 999;
System.out.println( a[2] );
System.out.println("b.length=" + b.length );
An Array Variable is a Reference
<<memory>>
What does "b = a" do? a <object>
What will be printed?
int [] a = { 2, 4, 6, 8 }; b <object>

int [] b = { 0, 0, 0 }; int[]
length=4
b = a; // Does what? 2
b[2] = 999; 4
6
System.out.println(a[2]); 8
System.out.println(
int[]
"b.length=" + b.length ); length=3
0
0
0
"b = a" copies the reference, not the array
<<memory>>
b = a;
a <object>
makes b refer to same array as a.
b <object>
b = a; int[]
length=4
b[2] = 999;
2
System.out.println(a[2]); 4
999
System.out.println( 8
"b.length=" + b.length );
int[]
length=3
0
0
0
The result:
<<memory>>
b = a;
a <object>
b[2] = 999;
System.out.println(a[2]); b <object>
System.out.println( int[]
length=4
"b.length=" + b.length );
2
4
6
999 8
b.length = 4
int[]
length=3
0
0
0
How do you really copy an array?
Here is one solution:

int[] a = { 2, 4, 6, 8 };

// java.util.Arrays.copyOf( ... )
// creates a new array for copy.
int[] b = Arrays.copyOf( a, a.length );

See also: System.arraycopy( ... )


Really Copying An Array
<<reference>>
To copy the contents of an array,
a <object>
you must copy each element.
<<reference>>
// copy each element of array
b <object>
for(int k=0; k<a.length; k++)
Array<int>
b[k] = a[k];
length=4
2
This copies all elements of a. 4
6
8
There is an easier way:
System.arraycopy(a, 0, b, 0, 4); Array<int>
length=4
2
4
6
8
System.arraycopy
System.arraycopy( src, src_start, dest, dest_start, length)

copies elements from src array to dest array.


It copies length elements only.

// copy each element of array


System.arraycopy(a, 0, b, 0, a.length );
"foreach" version of "for" loop
To iterate over every element of an array you can use a
special "for" syntax.

int [] array = { 2, 4, 6, 8, 10 };

// Iterate over all elements in array.


// "for each x in array do ..."

for(int x: array) System.out.println( x );


Array versus ArrayList (a List)
Array
// array of coins
Coin[] coins;
coins = new Coin[10];
coins[0] = new Coin(5);
coins[1] = new Coin(20);
System.out.println( coins[4] ); // print null
ArrayList is a kind of List
A List can hold any amount of data.
ArrayList is a kind of list.
List and ArrayList are in java.util.
// array of coins
Coin[] coins;
coins = new Coin[10];
coins[0] = new Coin(5);
coins[1] = new Coin(20);
System.out.println( coins[4] ); // print null
Array Exercises
 Write a method toString( double [] a ) that prints the
elements of the array, one per line.
 Write a method to reverse the elements of an array,
e.g. reverse( double [ ] a ) swaps a[0] and a[n-1],
swaps a[1] and a[n-2], ..., for n = a.length;
 write a method name argmax( double [ ] a ) that
returns the index of the maximum element of a.
 write a method name argmax( Comparable [ ] a ) that
returns the index of the maximum element of a. a[] is
any array of Comparable objects (has compareTo() ).
Useful Array Methods
a.length returns the length of array a[ ]. This is an
attribute, not a method.
Array methods defined in java.util.Arrays include:
Arrays.fill( a, value );
set all elements of a[ ] to a value
Arrays.sort( a );
sorts elements of a[ ]. sort works for primitive data
types, Strings, and array of any type where two
objects can be lexically compared using compareTo()
Arrays.sort( a, start_index, end_index );
sorts elements of a[ ] beginning at start_index
(inclusive) and ending at end_index (exclusive).
Useful Array Methods
Arrays.binarySearch( a, value )
return index of element in a[ ] equal to value
array a[ ] must already be sorted.
Arrays.equals( a, b )
returns true of a[] and b[] are the same size,
same type, and all elements are equal.
If the elements of a[ ] and b[ ] are objects (like Date)
then the object's equals method is used to compare
them: a[k].equals(b[k])
Arrays.toString( a )
return a string representation of a, such as:
[ "apple", "banana", "carrot", "durian" ]
Still More Array Methods
System.arraycopy( src, 0, dest, 0, length)
copy the elements of src[] into the array dest[],
starting at element 0 and copying length elements.

Knowing the Arrays class will save you time!


You should read the Java API for the java.util.Arrays class.
This class contains many useful methods for operations on
arrays. You will encounter many situations where you can use
these methods in your code.
If you don't know what methods are available, you will waste time
writing the same code yourself!
Array Examples

Some examples of using an array.


OK to skip these slides.
Example: find the maximum value
Let's write a method to find the maximum value of an array.
Example: double [ ] a = { 0.5, 2.8 -3.7, 18.0, 9.5 };
max( a ) is 18.0
/** Find the maximum value of array elements.
* @param a is an array of double values.
* @return the maximum value in a.
*/
declare parameter a as an array.
public static double max( double [] a ) {
// initialize max value to first element
double maxval = a[0];
// compare all elements of a to maxval
for( double x : a )
if ( x > maxval ) maxval = x;
return maxval;
}
Example: reverse a String
Write a method named reverse to reverse order of a String.
Example:
reverse("Hello there") returns "ereht olleH"
Algorithm:
H e l l o !
1. Convert the parameter (String)
to an array of characters. Use:
string.toCharArray( ) H e l l o !

2. Iterate over the 1st half of the char array. ! o l l e H


Swap characters with the 2nd half.

3. Convert char array into a String and return it. ! o l l e H


Code: reverse a String
String API methods:
"string".toCharArray( ) - create char array from String
new String(char [ ] c) - create new String from char array

public static String reverse( String text ) {


char[] c = text.toCharArray( );
// reverse the chars
for( int k=0; k < c.length/2; k++ ) {
int k2 = c.length - k - 1;
char temp = c[k]; c[k] = c[k2];
c[k2] = temp;
}
return new String( c );
}
Exercise: case-mangle a String
Write a method to mangle the case of a String, LiKe ThIs
Example:
mangle("hello there") returns "HeLlO tHeRe!"
Algorithm:
1. Convert the parameter (String)to an array of characters. Use:
string.toCharArray( )
2. Iterate over each character.
2a. if the character is not a letter do nothing.
2b. if the character is a letter change case and record what
was the last change (to uppercase or to lowercase).
3. Convert char array into a String and return it.
h e l l o t h e r e !
case
toggle
H e L l O t H e R e !
Resizing an Array
You cannot change the size of an array object.
To change the size, create a new array object and copy
elements from old array to the new array.
double [ ] a = new double[10];
for(int k=0; k < a.length; k++)
a[k] = input.nextDouble( );
/* oops! array is too small */

// create a larger array.


a = new double[100]; Error: the old values of a[ ] are lost!
Better Way to Resize Array
 Better: if you don't know how much data you must
store, use an java.util.ArrayList object.

 An ArrayList grows as needed.

 You can "convert" an ArrayList to an array of exactly the


needed size after you have all the data.

ArrayList<String> list = new ArrayList<>();


while( scanner.hasNext() ) list.add( scanner.next() );
// Create array of Strings for data in ArrayList
String[] names = new String[ list.length() ];
list.toArray( names ); // copy data into array
Creating an Array of Objects
// 1. define array reference
Date [ ] birthdays;
// 2. allocate storage
<<reference>>
birthdays = new Date[ 60 ];
// 3. create the objects birthdays <object>

// that go in the array!


for(int k=0; Object Storage Area:
k < birthdays.length; k++ )
Array<Date>
birthdays[k] = new Date( );
length=60
values= <Date>
Date ref
Date ref <Date>
birthdays[k] is an object reference.
Date ref
You must create the Date object that it ...
will refer to. Date ref <Date>
Example: Array of Objects (1)
Suppose we have a file on student names and student ID,
like this:
48540017 Watchara Srisawasdi
48540165 Kan Boonprakub
48540181 Keerati Tangjitsomkid
48540223 Thunthoch Laksulapan
48540231 Thanyawan Tarnpradab
48540249 Palawat Palawutvichai
48540256 Pitchatarn Lertudomtana
........ more data

We want to store the Student ID and name of each


student in an array for further data processing.
Example: Array of Objects (2)
Define a simple Student class with attributes for name and
Student ID.
public class Student {
String firstName; // attributes of student
String lastName;
String studentID;

/** constructor for new Student object */


public Student(String fn, String ln, String id)
{ studentID = id; // set the attributes
firstName = fs; // using parameters of
lastName = ls; // the constructor
}
... remainder of class definition omitted...
}
Example: Array of Objects (3)
We can create a new Student object like this:

Scanner input = new Scanner( System.in );

/* read data for a student */


String id = input.next( );
String first = input.next( );
String last = input.next( );

/* create a new student object */


Student s = new Student( first, last, id );

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy