-
Introduction
-
Must maintain references to multiple objects
-
E.g., 10 cars, 10 songs, 10 newspaper articles, 10 course descriptions
-
Could use files:
-
Keep all objects in a file
-
Find object in the file
-
But files are too slow! Why? I/O is expensive!
-
Objective: Read in data once from file into program (memory) - Perform
search in memory. Much faster. Easier to manipulate data.
-
How? Requires collection:
-
a group of objects
-
is also a Java object
-
individual objects are elements
-
We've seen search as an example. Other examples? Alphabetize a list.
Compute averages. Then count number above average, number below. Etc.
-
Collections of Objects
-
Overview:
-
Create a collection (constructor)
-
Add an object to the collection
-
Process the objects in the collection
-
java.util.Vector class
-
One way to create collections in Java (others too!)
-
Constructor - Vector () - creates a Vector object
-
Method - addElement (object reference)
-
Example:
import java.util.*;
...
Vector messages = new Vector ();
String aSingleMessage = "Enjoy spring break";
messages.addElement (aSingleMessage);
-
Using this, can we write a program that reads in data lines from a file?
Example:
import cucs.*;
import java.util.*;
...
Vector messages = new Vector ();
BasicDataReader inFile = new BasicDataReader ("mydata.txt");
while (!inFile.eof ())
messages.addElement (inFile.readLine());
How can we access elements? Stay tuned
-
Subclasses
-
Note that all objects in Java (i.e., instances of classes) can be treated
as an instance of the Object class.
-
So, a String, a Date, a Thermometer, etc. are also Objects
-
Why is this important?
-
Vectors are collections of Objects. Can enter any instance of any Java
class into a vector.
-
Accessing Objects in a Vector
-
Vector defines the methods:
int size () - number of elements
Object elementAt (int index) - return ith element
-
Example:
import cucs.*;
import java.util.*;
...
Vector messages = new Vector ();
BasicDataReader inFile = new BasicDataReader ("mydata.txt");
while (!inFile.eof ())
messages.addElement (inFile.readLine());
...
String tmp;
int s = messages.size();
int i = 1;
while (i <= s) {
tmp = (String) messages.elementAt (i);
System.out.println (tmp);
}
-
Collections of primitives
-
What about collections of ints, doubles, floats, etc?
-
Stay tuned.