Vous êtes sur la page 1sur 13

1.00/1.

001 - Lecture 8

Arrays and Vectors

Arrays-1
Arrays are a simple data structure
Arrays store a set of values of the same type
Built-in types (int, double, etc.) or
Objects (Students, Dates, etc.)
Arrays are part of the Java language
Arrays are objects, not primitives like int or double.
They are declared in the same way as other objects
int[] intArray= new int[20];
The array object has an integer data member,
length, that gives the number of elements in the
array:
int aSize= intArray.length; // aSize= 20

Each value is accessed through an index


intArray[0]= 4; intArray[1]= 77;

1
Arrays, p.2
Array indexes start at 0, not 1
An array with N slots has indices 0 through N-1
intArray has elements intArray[0] through intArray[19]
Array lengths cannot be changed once they are declared
Arrays can be initialized when declared
int[] intArray= {5, 77, 4, 9, 28, 0, -9};
// Note that new is implicit (not needed) in this case
Arrays of numerical values are zero when
constructed

Arrays, p.3
To copy an array, use arraycopy() method
int[] newArray= new int[15]; // Can be diff size
// arraycopy(fromArray, fromIndex, toArray, toIndex, count)
System.arraycopy(intArray, 0, newArray, 0, 15);
// Now intArray and newArray have separate copies of data
If we had just defined newArray without copying:
int[] newArray= intArray;
newArray[2]= -44; // This sets intArray[2]= -44 also
// intArray and newArray would just be two names for the
// same array. Remember in Java references refer to
// objects
You can create 2, 3, ..n dimensional arrays in Java.
int[ ][ ] twoDArray = new int[5][10];

2
Test Your Knowledge
1. Which of the following expressions does not declare and
construct an array?
a. int[ ] arr = new int[4];
b. int[ ] arr;
arr = new int [4];
c. int[ ] arr = {1,2,3,4};
d. int[ ] arr;
2. Given this code fragment:
int j= ?;
int[] data = new int[10];
System.out.print(data[ j ]);
Which of the following is a legal value of j?
a. -1
b. 0
c. 1.5
d. 10

Test Your Knowledge


3. Given this code fragment: What are the values of
the elements in array A?
int[] arrayA = new int[4]; a. unknown
int[] arrayB;
b. 0,0,0,0
arrayB = arrayA;
c. 4,0,4,0
arrayB[2]=4;
d. 4,0,0,0
arrayA[0]=arrayB[2];

4. How many objects are present after a. 1


the following code fragment has b. 2
executed? c. 10
float[] arrayA = new float[10]; d. 20
float[] arrayB;
arrayB = arrayA;

3
Test Your Knowledge
5. For which of these applications an array is NOT suitable?
a. Holding the scores on 4 quarters of a Basketball game
b. Holding the name, account balance and account number
of an individual
c. Holding temperature readings taken every hour through a
day
d. Holding monthly expenses through a year

6. Given the following code fragment: a. int index = 4; index>0; index--


int[] data = {1,3,5,7,11}; b. int index=0; index<4; index++
for(______________________) c. int index=0; index<data.length();
System.out.println(data[index] index++
); d. int index=0; index<data.length;
Fill in the blanks so that the program index++
prints out every element in the array
in order

Test Your Knowledge

7. What is the output of the following program? a. value before:10


class Test{ value after:0
public static void main ( String[] args ){ arr[0] before:10
int value = 10; arr[0] after: 0
int[] arr = {10,11,12,13}; b. value before:10
System.out.println("value before:"+value); value after:10
alterValue( value ); arr[0] before:10
System.out.println("value after:"+value); arr[0] after: 10
System.out.println("arr[0]before:"+arr[0]); c. value before:10
alterArray( arr ); value after:10
System.out.println("arr[0] after:"+arr[0]); arr[0] before:10
} arr[0] after: 0
public static void alterValue (int x ){ d. value before:10
x = 0; } value after:0
public static void alterArray (int[]a){ arr[0] before:10
a[0] = 0; } arr[0] after: 10
}

4
Example-Computing an Average

Given a list of numerical data items,


store them in an array and compute
the average value.
Well use a for loop to iterate over the
array entries.
Well put the computation of the
average in a separate method.

Computing Test Averages


public class AverageTest {
public static void main(String args[ ]) {
double[ ] testScores = new double[4];
testScores[0] = 80.0;
testScores[1] = 50.5;
testScores[2] = 90.0;
testScores[3] = 75.0;
System.out.println("Average is: " + average(testScores)); }

public static double average(double[ ] aDouble) {


double aver = 0.0; // initialize value
for(int i=0; i<aDouble.length; i++)
aver += aDouble[i]; // accumulate sum of values
return(aver/aDouble.length); //return average
}
}

5
Example
A. Create a TestArray class to store and manage
temperatures for a week
B. Start writing main():
Declare and construct an array of doubles, called
dailyTemp holding daily temperature data
Use an initializer list with braces { }
Mon Tue Wed Thu Fri Sat Sun
70 61 64 71 66 68 62

Using a for loop, print every element of the dailyTemp array in


reverse order (starting from Sunday and going backwards to
Monday)

public class TestArray {


public static void main(String args[])
{
int[] dailyTemp = {70,61,64,71,66,68,62};

for (int i=dailyTemp.length-1; i>=0; i--)


System.out.println(dailyTemp[i]);
}
}

6
Vectors
Vector class is a fancy version of an array
Vector can grow automatically as needed
Has capacity that is increased when needed
Has size, which is the actual number of elements
Vector can hold elements of different types
As long as each is an Object (reference),
Vector cant hold a basic type (not an int, double, etc.) !
You will use type casts or wrapper classes in Vectors
Wrappers are objects (e.g., Double) that hold built-ins

Vectors
Vectors are not in the core language
They are in package java.util, which you must
import:
import java.util.*; // At top of program

Vectors are slightly slower than arrays


Matters only in large scale numerical methods
Vectors have many methods you can
use

7
Vector Methods
void addElement(Object o) Adds object to end of vector,
increases vector size by one
int capacity() Returns capacity of vector

Object elementAt(int i) Returns object at index i

int indexOf(Object o) Finds first occurrence of


object; uses equals method
void insertElementAt(Object o, Inserts object at index i
int i)
boolean isEmpty() Returns true if vector has no
objects, false otherwise
void removeElementAt(int i) Deletes object at index i

void setElementAt(Object o, int Sets vector element at index i


i) to be the specified object
int size() Returns size of vector

Vector Constructors
Three basic forms (method overloading):
Vector()
Constructs an empty vector so that its internal data
array has size 10 and its standard capacity increment
is zero. Capacity will double whenever increased.
Vector(int initialCapacity)
Constructs an empty vector with the specified initial
capacity and with its capacity increment equal to
zero. Capacity will double whenever increased.
Vector(int initialCapacity, int
capacityIncrement)
Constructs an empty vector with the specified initial
capacity and capacity increment

8
A Vector Example
We will show a program that
generates a random number of lines
with random start and end points.
Well use a Vector object to hold the
lines, and use Vector methods to
control loop through the contents of
the Vector

Line class
import java.awt.*;
public class Line {
int x1,y1; // coordinates of start of line
int x2,y2; // coordinates of end of line
// constructor method for Line
public Line(Point p1, Point p2) { // Point class in AWT
x1 = p1.x;
y1 = p1.y;
x2 = p2.x;
y2 = p2.y; }
public void showLine() // Method to draw line segment
{
System.out.println("Coordinates are: ("+ x1+","+ y1+"),("+
x2+","+ y2+")" ); }
} // end of class Line

9
VectorExample class
import java.awt.*;
import java.util.*;
public class VectorExample {
static final double MAXCOORD = 10000.0;
static final int MAXLINES = 30;
public static void main(String args[ ]) {
int numLines = (int) (Math.random()*MAXLINES);
Vector vec = new Vector();
for (int i=0; i< numLines;i++) {
Line curLine = new Line(
new Point((int)(Math.random()*MAXCOORD),
(int)(Math.random() * MAXCOORD) ),
new Point( (int)(Math.random()*MAXCOORD),
(int) (Math.random() * MAXCOORD)));
vec.addElement(curLine); }
System.out.println ("Vector size: "+vec.size());
for (int i=0; i<vec.size(); i++)
((Line) vec.elementAt(i)).showLine(); }
} // end of VectorExample

Test Your Knowledge


1. Which of the following statements is NOT true about
Vectors?
a. Vectors are slightly faster than arrays.
b. Vectors can store elements of different types.
c. Vectors can increase in size to store more elements.
d. Vectors have methods to manage their content.

2. Considering myVector is a Vector that has been declared


and constructed, which of the following expressions is
always true?
a. myVector.size() >= myVector.capacity()
b. myVector.size() > myVector.capacity()
c. myVector.capacity() >= myVector.size()
d. myVector.capacity() > myVector.size()

10
Test Your Knowledge
3. What is the output of the following code fragment?
Vector myVector = new Vector(2);
myVector.addElement(new Integer(1));
myVector.addElement(new Integer(2));
myVector.addElement(new Integer(3));
System.out.println(myVector.size()+",+
myVector.capacity());

a. 2 , 3
b. 3 , 2
c. 3 , 4
d. 3, 3

Test Your Knowledge


4. Given the following code fragment:
Vector myVector = new Vector();
myVector.addElement("One");
myVector.addElement("Two");
myVector.addElement("Three");
myVector.addElement("Four");

Which one of the following expressions will modify myVector so it


looks like:
One; Two; Four
a. myVector.removeElementAt(myVector.elementAt(3));
b. myVector.removeElementAt(myVector.indexOf("Three"));
c. myVector.removeElementAt(3);
d. myVector.removeElementAt(myVector.elementAt(2));

11
Test Your Knowledge
5. Given the code fragment of question 4, which one of the following
expressions will modify myVector so it looks like:
One; Two; Three; Five
a. myVector[3] = "Five"
b. myVector[4] = "Five"
c. myVector.setElementAt("Five", myVector.indexOf("Four"));
d. myVector.setElementAt("Four", myVector.indexOf("Five"));

6. Given the code fragment of question 4, which one of the following


expressions will modify myVector so it looks like:
One; Two; Three
a. myVector.removeElementAt(2);
b. myVector.removeElementAt(myVector.lastElement());
c. myVector.removeElementAt(myVector.capacity());
d. myVector.removeElementAt(myVector.size()-1);

Test Your Knowledge


7. Given the following code fragment:
Vector myVector = new Vector();
myVector.addElement(new Integer(1));
myVector.addElement(new Integer(3));
myVector.addElement(new Integer(7));
Which one of the following expressions will modify myVector so it
looks like:
1357
a. myVector.addElementAt[new Integer(5)];
b. myVector.insertElementAt[new Integer(5), 2];
c. myVector.insertElementAt[5, 2];
d. myVector.insertElementAt[5, 3];

12
Exercise
A. Problem description
We want to store student names in a subject. MIT
subjects have between 1 and 900 students, so its hard
to anticipate the size of an array to hold the data. We
will use a Vector, since it can be dynamically sized.
B. Write the Java code.
1. Name your class MITCourse.
2. In its main() method:
Create a Vector students with capacity 5
Add 4 students Amy, Bob, Cindy and David to the
Vector. These students are Strings.
Add them to the Vector directly; dont declare 4 String
variables.

Exercise, p.2
3. Write a method to print all the elements in the
vector and its size and capacity.
Add a method printOutVector to the Course100 class:
public static void printOutVector(Vector vec) {
// Code goes here
}
4. Call printOutVector() method from main().
Pass the students Vector as the argument
5. Your output should be:
Amy
Bob
Cindy
David
Size: 4
Capacity: 5

Java is a trademark or registered trademark of Sun Microsystems, Inc. in the United


States and other countries.

13

Vous aimerez peut-être aussi