Académique Documents
Professionnel Documents
Culture Documents
001 - Lecture 8
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
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
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
4
Example-Computing an 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
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
7
Vector Methods
void addElement(Object o) Adds object to end of vector,
increases vector size by one
int capacity() Returns capacity 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
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
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"));
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
13