Java Reference
In-Depth Information
Class ArrayList . Class Vector has been in the API package java.util from the beginning. In
the latest version of Java, a new class ArrayList was added to package
java.util . It has roughly the same functionality as Vector : an object contains
size () elements and has a capacity; elements can be added, deleted, accesssed,
changed, searched for, and so on. Use either ArrayList or Vector —it is your
or your instructor's choice.
We introduce non-Java notation to help us talk about the elements of a
Vector v :
v[2] refers to the element numbered 2 .
v[h] refers to the element given by the value of expression h .
v[h..k] refers to the list of elements numbered h,h+1 , …, k .
v[h..] refers to the elements numbered h , h+1 , …, v.size() - 1
For example, if v is (or contains the name of) the object in Fig. 5.3, then
v[2] is the string "blue" , v[0..1] consists of 4 , "red" , and v[0..] is the whole
list of values.
In the notation v[i] , i is called the index of the element.
5.3.1
Creating and adding to a Vector
The declaration
Activity
5-5.1
Vector d= new Vector(5);
creates an instance of class Vector that can hold 5 objects and stores the name
of the instance in variable d . Instance d can hold 5 objects, but at the moment it
does not hold any; its capacity is 5 , but its size is 0 . (There is also a constructor
with no parameters, which creates a Vector with capacity 10 .)
Instance function add is used to add elements to a Vector . For example, the
following three statements add three objects to d , so Fig. 5.3 shows what d now
looks like.
a6
a1
Integer
4
Patient
0 6 1 8 2 4 3 ?
4 ?
a8
a4
size()
capacity()
etc.
String
String
"red"
"blue"
Figure 5.3:
A Vector with size 3 and capacity 5
Search WWH ::




Custom Search