Transcript Document

Arrays Continued
Passing by reference and
passing by value
Recap – Passing fundamental variables
 The value of the actual parameter is copied
into the formal parameter.
 This type of parameter passing is called
‘pass by value’.
public class PassByValueExample
{
public static void main(String args[])
{
// Setup Variable
int actualParameter;
// Assign value to variable
actualParameter =5;
System.out.println("Value of actualParameter is "+actualParameter);
// Point 1
// Call method with variable
doubleIt(actualParameter);
// Point 4
// Examine contents of variable to see if changed
System.out.println("actualParameter after doubleIt = "+actualParameter);
} // End entryPoint
public static void doubleIt(int formalParameter)
{
// Point 2
// Copy of parameter placed in variable formalParameter
// Alter value of variable
formalParameter = formalParameter * 2;
// Point 3
// Output current value of variable
System.out.println("Value of formalParameter is "+formalParameter);
} // End of double
} // End passByValueExample
Recap: Passing Objects as
parameters
 We have seen objects being passed as
parameters, however given what we now
know, what is actually happening?
 Answer: The contents of an object variable
(the address) is copied into a formal
parameter. The method can now use the
address to get access to the object.
 This type of parameter passing is called
‘pass by reference’
class ExampleClass
{
private String valueString="default";
public void changeString(String
receivedValue)
{
valueString = receivedValue;
} // End changeString
public String getValueString()
{
return valueString;
} // End getValueString
} // End ExampleClass
public class PassByReferenceExample
{
public static void main(String args[])
{
ExampleClass exampleObject;
// Point 1
// Setup the variable exampleObject to hold an address
// Create an object and put its address in exampleObject
exampleObject = new ExampleClass();
// Point 2
// Access the object
System.out.println("Contents of ValueString");
System.out.println(exampleObject.getValueString());
// Call the method changeObject with the address of exampleObject
changeObject(exampleObject);
// Point 5
// Check to see if the contents of exampleObject have changed
System.out.println("Contents of valueString");
System.out.println(exampleObject.getValueString());
} // End entryPoint
public static void changeObject(ExampleClass receivedObject)
{
// Point 3
// Copy the reference to an object into the variable receivedObject
// Change one of the variables in the object
receivedObject.changeString("hello");
// Point 4
// Finish the method
} // End changeObject
} // End PassByReferenceExample
Passing arrays
 Arrays are actually objects.
 Therefore if an array is passed as a
parameter what is passed is not a copy of
the array but the address of the array.
Example
public class ArrayPassingTest
{
public static void main(String args[])
{
int results[] ={5,3,7};
System.out.println("Values before change");
printArray(results);
changeArray(results);
System.out.println("Values after change");
printArray(results);
} // End entryPoint
public static void printArray(int arrayValues[])
{
for(int counter=0;counter<arrayValues.length;counter++)
System.out.println("Value in location "+counter+" is "+arrayValues[counter]);
} // End printArray
public static void changeArray(int arrayOfResults[])
{
arrayOfResults[0]=99;
arrayOfResults[1]=99;
arrayOfResults[2]=99;
} // End changeArray
} // End ArrayPassingTest
Two Dimensional Arrays
 A one-dimensional array stores a simple
index of values
 A two-dimensional array can be thought of
as a table of values, with an index of rows
and an index of columns.
 A two-dimensional array element is
referenced using two index values
Two Dimensional Arrays
 In Java we represent tables as twodimensional arrays.
 There is actually no explicit data structure
called “two-dimensional array” in Java. We
only have one-dimensional arrays in Java.
However, we can have an array of arrays,
and this is how a two-dimensional array is
implemented in Java.
Two Dimensional Arrays
 A two-dimensional
array element can
therefore be though of
as a cell in a table.
 To be precise, a twodimensional array in
Java is an array of
arrays.
0
1
0
1
2
1
2
4
2
3
6
3
4
8
Example
public class TwoDimArrayEg
{
public static void main(String args[])
{
int twoDTable[][];
twoDTable = new int[4][2];
for (int i = 0;i < 4; i++)
{
for(int j = 0; j < 2; j++)
{
twoDTable[i][j] = (i + 1) * (j + 1);//cell
}//inner for
}//outer for
for (int i = 0;i < 4; i++)
{
for(int j = 0; j < 2; j++)
{
System.out.print(twoDTable[i][j]+" ");
}//inner for
System.out.println();
}//outer for
}//end main
}//end class TwoDimArrayEg
Collections Overview
 A collection is a data structure (an object)
that can hold references to other objects,
usually of the same type.
 We have already looked at arrays (one
example of a collection)
Class Arrays
 java.util.Arrays
 Class arrays provide high level methods,
such as sort for sorting an array, equals for
comparing an array and fill for placing
values into an array.
public class UsingArrays
{
private int intArray[] = {1,2,3,4,5,6};
private double doubleArray[] = {8.4, 9.3, 0.2, 7.9, 3.4};
public UsingArrays()
{
filledIntArray = new int [10];
intArrayCopy = new int [intArray.length];
Arrays.fill (filledIntArray, 7);
Arrays.sort (doubleArray);
}
Arrays vs Vectors
 Grocery shopping list. To store items in the
shopping list, you would use a Vector object. You
may be wondering:
– Why should I use a Vector and not an Array for my
shopping list ?
 Since you do not know how many items are going
to be in the shopping list (maybe the user needs
milk and bananas today, but tomorrow needs
coffee, juice, and sugar) then you will want to use
the dynamic Vector object.
 Vectors, unlike Arrays, can grow and shrink during
their lifecycle.
Vectors



1.
"Arrays" of variable sizes are provided by the Vector
class
import java.util.Vector; // load Vector package
To create a vector, use three steps:
Declare a new vector object and assign it to the vector
variable.
v = new Vector(); // create an empty vector object
2. You may also add a number to specify the (initial)
capacity of the object
e.g., v = new Vector(5); // create a vector object with initial
capacity 5
3. Store things in the vector with the addElement method.
v.addElement(new Integer(1)); // add first vector element
Accessing, Changing, and
Removing Elements
 The size method returns the current number
of elements in the vector.
– v.size();
To remove elements from a vector
 v.removeElementAt(0);
To Add elements to the end of a Vector
 v.add(s); // adds s to the end of the Vector v
Vector Methods
There are many useful methods in the Vector class and its parent
classes. v is a Vector, i is an int index, o is an Object.
v.add(o)
adds Object o to Vector v
v.add(i, o)
Inserts Object o at index i, shifting elements up as necessary.
v.clear()
removes all elements from Vector v
v.contains(o)
Returns true if Vector v contains Object o
v.firstElement(i)
Returns the first element.
v.get(i)
Returns the object at int index i.
v.lastElement(i)
Returns the last element.
v.remove(i)
Removes the element at position i, and shifts all following
elements down.
v.set(i,o)
Sets the element at index i to o.
v.size()
Returns the number of elements in Vector v.
Adding to the Vector
import java.util.Vector;
public class MainClass {
public static void main(String args[]) {
Vector v = new Vector(5);
for (int i = 0; i < 10; i++) {
v.insertElementAt(i,0);
}
System.out.println(v);
}
}
Removing elements
import java.util.Vector;
public class MainClass {
public static void main(String args[]) {
Vector v = new Vector(5);
for (int i = 0; i < 10; i++) {
v.add(0,i);
}
System.out.println(v.capacity());
System.out.println(v);
v.remove(1);
v.removeElementAt(2);
System.out.println(v);
System.out.println(v.capacity());
}
}