java supports arrays an array is a collection of elements where each element is the same type. ...

67
Java supports arrays An array is a collection of elements where each element is the same type. Element type can be primitive or Object Each element is a single value The length of the array is set when it is created. It cannot change. Individual array elements are accessed via an index. Array index numbering starts at 0. Note: Some references claim that arrays in Java are Objects. THIS IS NOT TRUE. Arrays do exhibit some behaviour which is similar to objects, but they are not themselves, objects. Arrays in Java

Post on 22-Dec-2015

220 views

Category:

Documents


2 download

TRANSCRIPT

Java supports arrays

An array is a collection of elements where each element is the same type. Element type can be primitive or Object Each element is a single value The length of the array is set when it is created. It cannot change.

Individual array elements are accessed via an index. Array index numbering starts at 0.

Note: Some references claim that arrays in Java are Objects. THIS IS NOT TRUE. Arrays do exhibit some behaviour which is similar to objects,

but they are not themselves, objects.

Arrays in Java

ArraysAn array: an object that can hold a fixed number of values of the same type. Array to the right contains 4 int values.

5

7

4

-2

a0

A declaration has the basic form

<type> <variable-name> ;

A declaration of x looks as to the right. The declaration does not create the array, it only declares x. x’s initial value is null.

int[] x ;

0

1

2

3

Elements of the array are numbered 0, 1, 2, …, x.length–1;length is a variable, not a function, so don’t put () after it.

The type of the array to the right is

int[]

Here is a variable that contains the name of the array.

x a0int[]

Make everything as simple as possible, but no simpler. Einstein

Arrays int[] x ;

x null int

[]

0000

a0

x= new int[4]; 0123

Create an array object of length 4 and store its name in x x a0

int[]

-406-8

a0

0123

Assign 2*x[0], i.e. -8, to x[3]Assign 6 to x[2]

int k= 3;

x[k]= 2* x[0];

x[k-1]= 6;

x[2]= 5;

x[0]= -4;

-4050

a0

0123

Assign 5 to array element 2 and -4 to array element 0

x[2] is a reference to element number 2 of array x

Creating an array is a 2 step process It must be declared (declaration does not specify size)

It must be created (ie. memory must be allocated for the array)

Creating Arrays

type[] arrayName;declaration syntax:

note the location of the []

int[] grades; // declaration

grades = new int[5]; // Create array. // specify size// assign new array to // array variable

Syntax

• FormsElementType [] arrayName;ElementType [] arrayName = new ElementType [size];ElementType [] arrayName = array-literal;

• Where:– ElementType is any type– arrayName is the handle for the array

– array-literal is a list of literals enclosed in curly braces { }

Examples

• int [] a;

• int[] sequence = new int[5];

• int[] grades = {100, 96, 78, 86, 93};

int[] grades = new int[5];

When an array is created, all of its elements are automatically initialized 0 for integral types 0.0 for floating point types false for boolean types null for object types

Creating Arrays

0

0

0

0

0

4

3

2

1

0array indices

Note: maximum array index is length -1

grades

Because array elements are initialized to 0, the array should be initialized with usable values before the array is used. This can be done with a loop Arrays have a length attribute which can be used for bounds checking Elements are accessed using an index and []

Initializing and Using Arrays

int[] sequence = new int[5];

for (int i=0; i< sequence.length; i++){sequence[i] = i * 25;

}

array length: ensures loopwon't go past end of the arrayArray element being accessed. In

thiscase, it is being assigned a value.

Array initializers

Instead of

int[] c= new int[5];

c[0]= 5; c[1]= 4; c[2]= 7; c[3]= 6; c[4]= 5;

Use an array initializer:

int[] c= new int[ ] {5, 4, 7, 6, 5};

5

4

7

6

5

a0

array initializer: gives the values to be in the array initially. The values must all have the same type, in this case, int. The length of the array is the number of values in the list

No expression between the brackets [ ].

Computer science has its field called computational complexity;mine is called computational simplicity. Gries

The array is automatically created The array size is computed from the number of items in the list. More examples

Using initializer lists

int[] grades = {100, 96, 78, 86, 93};

type[] arrayName = {initializer_list};

String[] colours = { "Red", "Orange","Yellow", "Green","Blue", "Indigo","Violet"};

A use of an array initializer

public class D { private static final String[] months= new String[]{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; /** = the month, given its number m Precondition: 1 <= m <= 12 */ public static String theMonth(int m) { return months[m–1]; }}

Variable months is:static so that the object assigned to it will be created only once. private so that it cannot be seen outside class D.final so that it cannot be changed

Note that months[m–1] is returned,

since

months[0] = “January”,

months[1] is “February”,

Whenever and array is accessed, the index is checked to ensure that it within the bounds of the array.

Attempts to access an array element outside the bounds of the array will cause an ArrayIndexOutOfBounds exception to be thrown.

Array Bounds Checking

int[] sequence = new int[5];

sequence[0] = 50; // oksequence[1] = 60; // oksequence[-1] = 100; // Exception

sequence[5] = 30; // Exception

Processing Array Elements

• Access individual elements of an array using:– the name (handle) of the array– a number (index or subscript) that tells which

of the element of the array

• What value is stored in count[2]?

count [0] [1] [2] [3]

5 -7 9 27

Processing Array Elements

• Often a for( ) loop is used to process each of the elements of the array in turn.

for (int i = 0; i < NUM_STUDENTS; i++){ theScreen.print(STUDENTS[i]+ "\t"+scores[i]+"\t");theScreen.println(scores[i]-average);

}

• The loop control variable, i, is used as the index to access array components

Some exercises

• Write a program which finds the maximum of an array

• Write a program which finds the average of a list of integers

You may recall that the main method takes an array of String objects as a parameter. This array of Strings holds the command line parameters which were

passed to the java program when it was started

The main() method

public class HelloWorld{public static void main(String[] args){System.out.println("Hello World");

}}

Array holding command line parameters

Command line parameters

4

3

2

1

0

args

java HelloWorld This is a test, Jim

This

is

Jim

a

test,

name of class containing the main() method

Arrays with multiple dimensions can also be created.

They are created and initialized in the same way as single dimensioned arrays.

Multi-dimensional Arrays

type[][] arrayName;declaration syntax:

each [] indicates another dimension

int[][] grades = new int[20][5];for(int i = 0; i< 20; i++)for(int j = 0; j<5; j++)

grades[i][j] = 100;

String[][] colours = {{"Red", "Green", "Blue"}, {"Cyan", "Magenta", "Yellow"}, {"Russet", "Mauve", "Orange"}};

Type of d is int[][] (“int array array”,

“an array of int arrays”)

To declare variable d:

int d[][].

To create a new array and assign it to d:

d= new int[5][4];

To reference element at row r column c:

d[r][c]

number of rows

number of cols

Two-dimensional arrays

5 4 7 3

b

0 1 2 3 b.lengthone-dimensional array

5 4 7 3

4 8 9 7

5 1 2 3

4 1 2 9

6 7 8 0

d

0 1 2 3

0

1

2

3

4

rectangular array: 5 rows and 4 columns

Array Parameters

• Methods can accept arrays via parameters• Use square brackets [ ] in the

parameter declaration:public static double sum (double [] array){ for (int i=0; i < array.length; i++) . . . }

• This works for any size array– use the .length attribute of an array

to control the for loop

Methods that Return Array Values

• A method may return an array as its resultpublic static double [] readArray(){ . . . // ask for now many, ndouble result[] = new double[n]; for (i = 0; i < n; i++) { theScreen.print("Enter …"); result[i] = theKeyboard.readDouble(); }return result;

}

Declare return typeDeclare return type

Declare local array for receiving input

Declare local array for receiving input

Local array is returnedLocal array is returned

The Assignment Operation

Java provides a few operations to use with arrays, including assignment

• Consider:int [] alist = { 11, 12, 13, 14};int [] blist;blist = alist;

• Recall that alist and blist are handles– alist contains an address of where the numbers are– blist now contains that same address– blist does not have a copy of alist

Array Cloning

• To actually create another array with its own values, Java provides the .clone() method

int [] alist = { 11, 12, 13, 14};

int [] blist;

blist = alist.clone();

• Now there are two separate lists of numbers, one with handle alist, the other with handle blist

Array Cloning with Reference Types

• Recall previous declaration:

• Consider:String[] s_list = STUDENTS.clone():

• This will create another list of handles, also pointing to the names

STUDENTS [0] [1] [2] [6]

Bashful Doc . . . Sneezy

Elements are handles for String values

Sometimes called a "shallow copy"

operation

Sometimes called a "shallow copy"

operation

Array Equality

• Java has an equals() method for classesif (a1.equals(a2)) …

• If a1 and a2 are arrays, the equals() method just looks at the addresses the handles point to

• They could be pointing to different addresses but the contents of the array still be equal– It is the contents that we really wish to compare

Array Equality

• We must write our own method to compare the arrays– they both must have the same length– then use a for( ) loop to compare element by

element for equality

if (list1.length==list2.length){ for (int i = 0; i < list1.length; i++) if (list1[i] != list2[i]) return false; return true; }else return false;

As soon as one pair of elements is found not equal, the method returns falseAs soon as one pair of elements is found not equal, the method returns false

Exercises

• Write Programs to• 1: given an array of 20

Integers print out all those > 15 and print out their positions.

• 2: Given an array of 20 integers, delete the 5th element so that:

• Before• 17-15-14-23-22-19-etc• After• 17-15-14-23-19-etc

a b

Procedure swap

public class D { /** = Swap x and y */ public static void swap (int x; int y) { int temp= x; x= y; y= temp; }}

…. swap(a, b);

5 3

The call will NOT swap a and b. Parameters x and y are initialized to the values of a and b, and thereafter, there is no way to change a and b.

swap: 1

?

x ytemp

5 3

?

frame for call just after frame is created.

Exercise

• Write a program which takes an array and reverses it.

More Exercises

• Describe in detail how the following code would process the following list

• {7,3,4,6,8}

Bubblesort• public void bubbleSort()

{int out, in;for(out=nElems-1; out>1; out--) // outer loop (backward)

{ for(in=0; in<out; in++) // inner loop (forward)if( a[in] > a[in+1] ) // out of order?swap(in, in+1); // swap them} // end bubbleSort()//--------------------------------------------------------------private void swap(int one, int two)

• long temp = a[one];a[one] = a[two];a[two] = temp;}

Linear search

public class D { /** = the first occurrence of c in b[h..k-1] —

= k if c is not in b[h..k-1]*/ public static void swap (int c, int[] b, int h; int k) { int t= h;

// { invariant: c is not in b[h..t-1] }

for (t= h; t != k; t= t+1) { if (b[t] == c)

return t;}

// { R: c is not in b[h..k-1] }return k;

}}

Vectors: More Object-Like Arrays

• Many programmers find it odd that arrays have a different syntax than do most objects. Others find it inconvenient that arrays have a fixed size. To handle these, and similar, objects, Java provides an array-like structure called java.util.Vector. Vectors are much like arrays in that Vectors are

• homogeneous - vectors typically store only one kind of element;

• indexed - vectors permit clients to access values using integers that indicate position;

• efficient - vectors provide fast access to values.

However, unlike arrays

• vectors are expandable - you can continue to add elements to a vector, even if the vector has grown beyond its original size.

• As you are likely to discover, it is fairly easy to build your own Vector class from the underlying array structures; in essence, you have a field that contains an array, and you build a new array and copy over values whenever the original array gets too big.

• For now, you can rely on the built-in class.

Java.util.vector

• The standard vector class, java.util.Vector is a parameterized class. That is, when you create an object in that class, you must supply the underlying type.

• For example, to create a vector of strings, you would write

• Vector<String> stuff = new Vector<String>();

more

• Once you have created a vector (or obtained one from another method or class), you can

• add a value to the end of the vector with the add(T val) method;

• obtain a value from a vector with the get(int index) method;

• change the value in a particular position with the set(int index, T val) method; and

• determine the number of values in the vector with the size() method.

Difference between Vector and array --both used to contain a bunch of thingsDeclaration: int[] a; Vector v;

Elements of a: int values Elements of v: any Objects

Array always has n elements Number of elements can change

Creation: a= new int[n]; v= new Vector();

Reference: a[e] v.get(e)Change element: a[e]= e1; v.set(e, e1);Array locations a[0], a[1], a[2] are in successive locations in memory. Access is guaranteed take same, time no matter which one you reference.

Elements are all the same type (a primitive type or some class type)

You can’t tell how Vectors are stored in memory. Referencing and changing elements done through method calls

Elements can be of any Object type (but not a primitive type), and casting may be necessary when an element is retrieved.

Vector methods• vec.size() -- This function returns the current size of the vector. Valid

positions in the vector are between 0 and vec.size() - 1. Note that the size can be zero, and it is zero when a vector is first created.

• vec.addElement(obj) -- Adds an object onto the end of the vector, increasing the size of the vector by 1. The parameter, obj, can refer to an object of any type.

more

• vec.elementAt(N) -- This function returns the value stored at position N in the vector. N must be an integer in the range 0 to vec.size() - 1. If N is outside this range, an error occurs.

• vec.setElementAt(obj, N) -- Assigns the object, obj, to position N in the vector, replacing the item previously stored at position N. The integer N must be in the range from 0 to vec.size() - 1.

• vec.insertElementAt(obj, N) -- Moves all the items in the vector in positions N and above up one position, and then assigns the object, obj, to position N. The integer N must be in the range from 0 to vec.size(). The size of the vector increases by 1.

More methods• vec.removeElement(obj) -- If the specified object occurs somewhere in the

vector, it is removed from the vector. Any items in the vector that come after the removed item are moved down one position. The size of the vector decreases by 1. The value of the parameter, obj, must not be null.

• vec.removeElementAt(N) -- Deletes the element at position N in the vector. N must be in the range 0 to vec.size() - 1. Items in the vector that come after position N are moved down one position. The size of the vector decreases by 1.

more

• vec.setSize(N) -- Changes the size of the vector to N, where N must be an integer greater than or equal to zero. If N is bigger than the current size of the vector, new elements are added to the vector and filled with nulls. If N is smaller than the current size, then the extra elements are removed from the end of the vector.

• vec.indexOf(obj, start) -- A function that searches for the object, obj, in the vector, starting at position start. If the object is found in the vector at or after position start, then the position number where it is found is returned. If the object is not found, then -1 is returned. The second parameter can be omitted, and the search will start at position 0.

Vector example• /*

•   This Java Example shows how to sort the elements of java Vector object using•   Collections.sort method.• */•  • import java.util.Vector;• import java.util.Collections;•  • public class SortJavaVectorExample {•  • public static void main(String[] args) {•  • //create Vector object• Vector v = new Vector();•  • //Add elements to Vector• v.add("1");• v.add("3");• v.add("5");• v.add("2");• v.add("4");•  

continued• /*•   To sort a Vector object, use Collection.sort method. This is a•   static method. It sorts an Vector object's elements into ascending order.•   */• Collections.sort(v);•  • //display elements of Vector• System.out.println("Vector elements after sorting in ascending order : ");• for(int i=0; i<v.size(); i++)• System.out.println(v.get(i));•  • }• }•  • /*• Output would be• Vector elements after sorting in ascending order :• 1• 2• 3• 4• 5

Another vector example

• /*

•   Add an element to specified index of Java Vector Example

•   This Java Example shows how to add an element at specified index of java

•   Vector object using add method.

• */

•  

continued• import java.util.Vector;•  • public class AddElementToSpecifiedIndexVectorExample {•  • public static void main(String[] args) {• //create an Vector object• Vector v = new Vector();•  • //Add elements to Vector• v.add("1");• v.add("2");• v.add("3");•  

continued• /*•   To add an element at the specified index of Vector use•   void add(int index, Object obj) method.•   This method inserts the specified element at the specified index in the•   Vector. •   */• v.add(1,"INSERTED ELEMENT");•  

• /*•   Please note that add method DOES NOT overwrites the element

previously•   at the specified index in the Vector. It shifts the elements to right side•   and increasing the Vector size by 1.•   */•  

finally• System.out.println("Vector contains...");• //display elements of Vector• for(int index=0; index < v.size(); index++)• System.out.println(v.get(index));•  • /*•   To append an element at the end of Vector use•   boolean add(Object o) method.•   It returns true as a general behavior of the Collection.add method

and•   appends the specified element at the end of Vector.•   */• }• }•  

Finally

• /*

• Vector contains...

• 1

• INSERTED ELEMENT

• 2

• 3

• */

Item Class

• public class Item {• protected String itemname;• protected String manufacturer;• protected String description;• protected double price ;• protected int quantity;• protected int reorderlevel;••

Constructor• // the Item class has one constructor• public Item(String startName,String startManufacturer, String

startDescription,int startQuantity, int startReorderlevel, double startPrice) {

• • itemname = startName;• description = startDescription;• manufacturer = startManufacturer;• quantity = startQuantity;• reorderlevel= startReorderlevel;• price = startPrice;• }••

Observer methods• // the item class has seven methods• public String getname() {• return itemname;• }•• public String getmanufacturer() {• return manufacturer;• }• public String getdescription() {• return description;• }• // the item class has seven methods• public double getprice() {• return price;•

• }• // the item class has seven methods• public int getquantity() {• return quantity;• }• public void setquantity(int amt1) {• quantity= amt1;• }• // the item class has seven methods• public int getreorderlevel() {• return reorderlevel;• }•• }

Class extension

Grocery Item

• public class GroceryItem extends Item {•• // the Item class has one constructor• public GroceryItem(String startName,String

startManufacturer, String startDescription,int startQuantity, int startReorderlevel, double startPrice) {

• super(startName, startManufacturer, startDescription, startQuantity, startReorderlevel, startPrice);

• }•

Extra methods

• public void outwarning() {• if (super.getquantity() <= super.getreorderlevel())• System.out.println("Reorder now");• }

• public void outdisplay() {• String str = "stock levels " + super.getquantity(); • System.out.println(str);• }

Note use of super class methods

• public void buy(int amt) {• int newamt;• newamt = super.getquantity() + amt;• super.setquantity(newamt);• }•• public void sell(int amt) {• int newamt;• newamt = super.getquantity() - amt;• super.setquantity(newamt);• }• }

Program to use this

• public class Item1test• {

• Item1test()• {• // create a GradeBook object and assign it to myGradeBook• // call the constructor for the class GradeBook• GroceryItem d1 = new GroceryItem("Wiskat","cndfoods", "catfood",100, 50,

1.79);• GroceryItem d2 = new GroceryItem("Barkat","cndfoods", "dogfood",130,

40, 9.53);

• if (d1.getquantity() > d2.getquantity())• System.out.println("item" + d1.getname() + "has more");• else• System.out.println("no "+"item " + d2.getname()+"has more");

• d1.outwarning();• d2.outwarning();• d1.outdisplay();• d2.outdisplay();• d1.sell(80);• d2.buy(34);• d1.outwarning();• d2.outwarning();• d1.outdisplay();• d2.outdisplay();•• } // end main

• public static void main (String[] args) {

• // Start the program running from its constructor

• new Item1test();}

• } // end class

Another involving vectors

• import java.util.Vector;• public class Item2test

• {

• Item2test()• {• GroceryItem d1 = new GroceryItem("Wiskat","cndfoods",

"catfood",100, 50, 1.79);• GroceryItem d2 = new GroceryItem("Barkat","cndfoods",

"dogfood",130, 40, 9.53);• GroceryItem d3 = new GroceryItem("birdseed","bfoods",

"seed",1200, 50, 1.79);• GroceryItem d4 = new GroceryItem("fishfood","goldfoods",

"pellets",170, 40, 9.53);

• Vector v = new Vector();

• v.add(d1);

• v.add(d3);

• v.add(1,d4);

• v.get(1);

• NoteVector v = new Vector();

• v.get(1); wont give an error but you wont be able to use groceryitem methods with it we need to use wrapper class

• GroceryItem d5 = (GroceryItem)(v.get(1));

• d5.outdisplay();

• d5 = (GroceryItem)(v.get(0));

• d5.outdisplay();

• //d5 = v.get(2);

• //d5.outdisplay();

• //d5 = v.get(2);

• //d5.outdisplay();

• If comment lines removed error will follow

To finish off

• v.remove(0);• v.add(0,d5);• d5 = (GroceryItem)(v.get(0));• d5.outdisplay();

• } • public static void main (String[] args) {• new Item2test();}

• }

Note

• We can reset d5

• d5 = (GroceryItem)(v.get(0));