Vector classes are used to hold a set of objects, and because Java does not support dynamic arrays, vectors can be used to implement functions similar to dynamic arrays. Vector is a good choice if you want to store a set of objects in a data structure, but you cannot determine the number of objects.
Example: Store each digit of a sequence of numbers entered on the keyboard in a vector object, and then print the result of the addition of the numbers on the screen.
Import java.util.*; Both the vector and enumeration interfaces are in this package.
public class Testvector
{
public static void Main (string[] args)
{
Vector v=new vector ();
int b=0;
int num=0;
System.out.println ("Please enter Number:");
while (true)
{
Try
{
B=system.in.read (); Reads a byte of content from the keyboard
}
catch (Exception e)
{
E.printstacktrace ();
}
if (b== ' \ r ' | | b== ' \ n ')//If it is a carriage return or line break, exit the while loop, which is a string of data input complete
{
Break
}
Else
{
num=b-' 0 ';
/* Because the input is a character number, its value is its ASCII code, such as ' 0 ' = 32; ' 1 ' = 33,
So in order for the input ' 1 ' to be 1 in the computer, you must subtract 32, that is, ' 0 ' */
V.addelement (new Integer (num)); Storing numbers in vectors
}
}
int sum=0;
Enumeration e=v.elements ();
To remove all elements from the vector, you must use the elements () method, which returns a enumeration interface.
while (E.hasmoreelements ())//If the current indicator also points to an object, there is still data
{
Integer intobj= (integer) e.nextelement ();
Takes out the object that the current indicator refers to and points the indicator to the next object.
Sum+=intobj.intvalue (); Extracts an integer wrapped in an integer object and adds it to sum.
}
SYSTEM.OUT.PRINTLN (sum);//print out this and
}
}
The enumeration Nextelement () method returns the object indicated by the indicator, and then points the indicator to the next object.
Since vectors can store various types of objects, the compiler cannot know what type of object is stored, so even if we know what type is stored in it, it is also shown what type it is, as in this example (Integer) e.nextelement ();
The enumeration interface implements a mechanism through which we can implement access to all objects using only the hasMoreElements () method and the Nextelement () method.
Vector class and enumeration interface