Friday, November 27, 2015

Produce A Vector Of The Class In Java

The Java programming language has a data storage device called a vector. A vector stores data similar to an array, in that stored data can be accessed directly by index. However, unlike an array, the vector doesn't have a defined size and can grow or shrink as items are added and removed from it. Vectors can store many different items. You can create a vector that stores instances of classes, also known as objects. The syntax for using vectors is quite simple and you can get started with creating vectors of class instances right away.


Instructions


1. Load the NetBeans IDE by clicking on its program icon. When the program loads, navigate to "New/New Project" and select "Java Desktop Application" from the list on the right-hand side of the screen. A new project is created, and a blank desktop application window appears in the main workspace.


2. Import the Vector container class by writing the following at the top of the source code file:


import java.util.*;


3. Declare a vector by writing the following code within the curly brackets of the main function:


Vector v = new Vector();


4. Create an instance of the Integer class, or any other class you wish to store in the vector. To create an instance of the Integer class, write the following below the line written in the previous step:


Integer tmp = new Integer(20);


5. Add the instance of the Integer class to the vector by writing the following below the line written in the previous step:


v.add(tmp);


6. Print out the item you just added using the println() function. Write the following line of code below the line written in the previous step:


System.out.println("The object at index 0 is: " + v.elementAt(0));


7. Execute the program by pressing the "F6" key. The program executes and creates a vector storing one instance of the Integer class. This is then printed to the console.