Java Simple Vector Example

The Java Vector class implements a grow-able array of objects. Similar to an array, the vector contains components that can be accessed using an integer index. However, the size of a Vector can shrink or grow as needed to accommodate adding and removing objects after the Vector has been created.

The key difference between Arrays and Vectors in Java is that Vectors are dynamically-allocated. Keep in mind that just like any other data collection, it is always a good idea to parameterize to the type of object your storing. In our example, we are storing Strings.


Java Simple Vector Source Code

package com.jcd.java.tutorials;

import java.util.Vector;

public class JavaSimpleVector 
{

	public static void main(String[] args) 
	{

		//Create a new Vector Object to hold Strings
		Vector<String> jcdVector = new Vector<String>();
		
		//Add Strings to our Vector
		jcdVector.add("Java");
		jcdVector.add("Code");
		jcdVector.add("Depot");
		jcdVector.add("Com");
		
		//Use Enhanced for loop to iterate vector elements
		for(String jcdString : jcdVector) 
		{
			System.out.println("Vector Element: "+jcdString);
		}
		
		System.out.println();
		
		//Print out specific vector element using index
		System.out.println(jcdVector.get(0));
		System.out.println(jcdVector.get(1));
		System.out.println(jcdVector.get(2));
		System.out.println(jcdVector.get(3));
		
	}

}


Java Simple Vector Output

Vector Element: Java
Vector Element: Code
Vector Element: Depot
Vector Element: Com

Java
Code
Depot
Com


Add a Comment

Your email address will not be published. Required fields are marked *