Vector in Java

Vector in Java

Vector in Java


Vector in Java

Introduction
Vectors in Java uses data in a linear fashion like Array. But it implements a dynamic array that can grow or shrink as and when required to accommodate adding and removing data item. In the Java 2 SDK, the Vector class has been included in the Collection framework to implement the List interface and it comes under the java.util package. The Vector class is favored over the ArrayList class when we are creating a multi-threaded application.

  • The Vector class is similar to ArrayList class but Vector is synchronized(the main facet of Vector class is that it is thread-safety. ).
  • The Vector class is created dynamic Array which can grow and shrink.
  • Vector class is a child class of AbstractList class and implements on List interface
  • Duplicate element/objects are allowed in Vector
  • Insertion order is maintained
  • It allows NULL insertion
  • Vectors don’t support primitives data types like short, int, double, char, etc.

Advantages of Vector in Java

  1. Due to its Dynamic size, memory wastage is not happening.
  2. Vector class is synchronized and it helps in the multithreaded program and helps to check data corruption.
  3. Vectors have some legacy methods which can be implemented only on vector class and not on the ArrayLists class.
Note: The Vector class may reduce the performance of the developed application as it is thread safety and it only allowed one thread as it locked the thread and the remaining thread have to wait until a thread released the object lock. So it is recommended that if we do not need thread safety, then we should use the ArrayList class instead of Vector class.  

The Vector class defines the following constructors

public Vector() This a constructor creates an empty vector and its initial data array size is 10
public Vector(int n) This A constructor creates an empty vector with specified size n.
Vector (int initSize, int incrSize) This form of constructor creates an empty vector with its initial and increment capacity.
Vector (Collection c) This a constructor creates a vector containing the elements of the specified collection c.

Apart from the above constructor's Vector define three protected data member which are as follows
protected int capacity increment
This data member of the vector is automatically incremented when its size becomes greater than its capacity.
 protected int  elementCount
The number of valid elements in the vector.
protected int elementData[]
The array holds the elements of the vector.


Exmpale
import java.util.*;
public class TheVectorClassExample
{
    public static void main(String args[]) { 
    
        Vector<String> student = new Vector<String>(4); 
        //Adding elements to a student Vector
        student.add("Zainab"); 
        student.add("Sachin");
        student.add("Junaid"); 
        student.add("Salim"); 
        student.add("Ashis"); 
        student.add("Deva"); 
        student.add("Danny"); 

        //Checking the size and capacity of Vector
        System.out.println("The Size of Vector is: "+student.size()); 
        System.out.println("Default capacity is: "+student.capacity()); 

        //Display Vector elements 
        System.out.println("Vector element is: "+student); 
        student.addElement("Rat"); 
        student.addElement("Cat"); 
        student.addElement("Deer"); 
        //Again check size and capacity after two insertions 

        System.out.println("Size after addition: "+student.size()); 
        System.out.println("Capacity after addition is: "+student.capacity()); 

        //Display Vector elements again 
        System.out.println("Elements are: "+student); 

        //Checking if Tiger is present or not in this student or         
        if(student.contains("Tiger")) 
        { 
            System.out.println("Tiger is present at the index " +student.indexOf("Tiger")); 
        } 
        else 
        { 
            System.out.println("Tiger is not present in the list."); 
        } 

        //Get the first element 
        System.out.println("The first animal of the studenttor is = "+student.firstElement());  

        //Get the last element 
        System.out.println("The last animal of the studenttor is = "+student.lastElement());  

        // Using Enumeration
        Enumeration en = student.elements();
        System.out.println("\nStudent are:");
        while(en.hasMoreElements())
            System.out.print(en.nextElement() + " ");
    } 
}

How to copy a Vector into an Array?

import java.util.*;
public class Vector2JavaArray
{
    public static void main(String[] args) {
 
        // Vector class object
        Vector<String> vector = new Vector<String>();
        vector.add("Aman");
        vector.add("Bimal");
        vector.add("Jamil");
        vector.add("Sachin");
        vector.add("Vikas");
        System.out.println("Actual vector elements:" + vector);
        
        // Create an Array 
        String[] copyArray = new String[vector.size()];
        
        // Here we use copyInto Method to copy 
        vector.copyInto(copyArray);
        
        System.out.println("Copied Array as OUTPUT:");
        for (String name : copyArray) 
        {
            System.out.println(name);
        }
    }
}
Sample output
Actual vector elements:[Aman, Bimal, Jamil, Sachin, Vikas]
Copied Array as OUTPUT:
Aman
Bimal
Jamil
Sachin
Vikas


More Articles
Java Access Modifiers

Java Access Modifiers

Java Access Modifiers
Java Access Modifiers

Java Access Modifiers

In this tutorial, I’ll describe how Java access modifiers work in detail. They manage the visibility and their members (methods and data). There are three Java access modifiers public, private, and protected. There is another modifier namely default which is implemented by default.
Java Access Modifiers Explained With Examples
Access Modifier
within class
within package
outside package by subclass only
outside package
Outside Class
Public
Y
Y
Y
Y
Y
Protected
Y
Y
Y
Y
N
Private
Y
N
N
N
N
Default
Y
Y
Y
N
N

Public Access Modifier

The accessibility of this modifier visible everywhere. We can say that public modifier doesn’t put any restriction on the access. This indicate that any public class, method, variable, interface, or constructor is accessible throughout the package. But if it belongs to another package then we need to import it. It has a broad scope among all other modifiers. The public access modifier can be useful to classes and interfaces along with methods, data members and variables.
Example of public modifier
public class FirstClass
{
    public void display()
    {
        System.out.println("I am Public Modifier");
    }
}
public class SecondClass
{
   public static void main()
   {
       FirstClass ob = new FirstClass();
       ob.display();
    }
       
}

Output:

I am Public Modifier
Here, in SecondClass, we can instantiate the FirstClass because its access modifier is public. The variables and methods inside the SecondClass class are also public. Hence, you are able to use it directly in your L SecondClass.

Private Access Modifier
This modifier can access Data members, methods and constructors within the class.             We cannot develop subclasses to that class which has only private constructors. Classes or interface cannot be declared as private because private modifier will make the class useless.
public class PrivateExampleBase
{
   private void display()
    {
        System.out.println("I am Private Modifier");
    }
}
In PrivateExampleBase display() method declare as private and when we called display() method from PrivateExampleDrive then it will generate error “display() has private access in PrivateExampleBase”
public class PrivateExampleDrive
{
   public static void main()
   {
       PrivateExampleBase ob = new PrivateExampleBase();
       ob.display();
    }
}
Another Example: This program is used to show that private members of a class can be accessed in the class only

class StudentClass {
    //private members of the class

    private int rollNo; // define as a private modifier

    private void show() {
        rollNo = 10;
       
        System.out.println("RollNo = " + rollNo);
    }
}

public class PrivateDataMember {
    public static void main(String args[]) {
        //creating StudentClass object
        StudentClass ob = new StudentClass();
        System.out.println(ob.rollNo);
        ob.show();
    }
}
In PrivateDataMember class we will try ti access private data member(rollNo) and also try to access show() method. But it will not be accessecible as it is define as private. And it'll display error as "Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - rollNo has private access in MyFirstApp.StudentClass
            at MyFirstApp.PrivateDataMember.main(PrivateDataMember.java:15)"
Note: Private constructor cannot able to create an instance in another class.

Protected Access Modifier

The protected access modifier methods or data members are accessible within the same package or subclasses in a different package. We cannot declared protected in the classes because it used in the parent-child relationship. But the protected access modifier can be used on the data member, method and constructor.

package MyFirstApp;

class StudentClass {
    //protected members of the class
    protected int rollNo;
    protected void show()
    {
        rollNo = 10;
        System.out.println("RollNo = " + rollNo);
    }
}
public class ProtectedDataMember {
    public static void main(String args[]) {
        //creating Student class object
        StudentClass ob = new StudentClass();
        ob.show();
    }
}

Default Access Modifier

If we don’t mention any access modifier for a class, method or data member then we can say it is a default modifier. It can be accessed into all classes within the same package only. The default access modifier is also sometimes known as the package access modifier.

import java.util.Scanner;
public class Palindrom {
    int n, rev, m, a; // default access modifier
    void input() // this method contain no modifier
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number:");
        n = sc.nextInt();
        m = n;
    }

    void palin() // this method contain no modifier
    {
        rev = 0;
        while (m != 0) {
            a = m % 10;
            rev = rev * 10 + a;
            m /= 10;
        }
        if (rev == n) {
            System.out.println("Palindrom");
        } else {
            System.out.println("Not Palindrom");
        }

    }

    public static void main(String[] args) {
        Palindrom ob = new Palindrom();
        ob.input();
        ob.palin();
    }
}

More Tutorials

Linked List in Java

ArrayList in Java

Basic Features of java


Linked List in Java

Linked List in Java

Linked List in Java

Linked List in Java

Introduction to Linked List

The array data structure has some shortcoming. The size of an array must be defined when the program is developed. Here we must define the size of data, but during the execution of a program, the size we
define might be unused and lots of space is wasted and if data is more then the array size then this could lead to an undesirable effect on the whole program. There is another problem with using Array is that of insertion and deletion. In case of insertion of data into an array, we must shift data one position right and in case of deletion, we should shift data to the left. If there is huge data in an array then insertion and deletion required a huge amount of time.
These problems will be overcome by the Linked List data structure. In Linked list representation of data structure, each element stored in a node and node has two part one is data and another is reference or address of the second node.

Definition of LinkedList:

Linked List is a linear structure which has a node linearly. It implements List and Deque interfaces.

Linked List representation
Picture of LinkedList

Advantages of LinkedList:

  • It is a dynamic data structure which allocates the memory as when required.
  • It has no pre-allocated memory like an array.
  • Insertion and Deletion easily be done and it is faster.
  • It can contain duplicate data.
Disadvantages of LinkedList:

  • It is arranged sequentially that is why access time is more.
  • Memory is wasted due to pointer/ reference part.
  • To access of nth element of a Linked List is O(n).
Usage of Linked List

It is used to implement abstract data type such as Stack, Queue, List, Graphs


Java Linked List 

In Java, Linked List implementation is done in doubly linked list and it has List and Dequeue interfaces.

Linked List in Java


LinkedList Constructors

LinkedList () : initializes an empty LinkedList implementation.
LinkedList (Collection c) : initializes a LinkedList containing the elements of the specified collection, in the order they are returned by the collection’s iterator.

 LinkedList Method

 boolean add(Object o): This method is used to appends the specified element to the end of a list.
void add(int index, E element): This method is used to inserts the specified element at the specified position index in a list.
boolean addAll(Collection<? extends E> c)          This method is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator.
void addFirst(Object o): It inserts the given element at the beginning of a list.
void addLast(Object o): It appends the given element to the end of a list.
void clear()         This method is used to eliminate / delete all the elements from a list.
int size()  This method is used to returns the total number of elements in a list
Object clone()   It is used to return a shallow copy of an ArrayList.
boolean contains(Object o): return true if the list contains a specified element, else false.
boolean remove(Object o): It removes the first occurrence of the specified element in a list.
Object getFirst() This method is used to returns the first element in a list.
Object getLast() This the method is used to returns the last element in a list.
int indexOf(Object o)   This method is used to returns the index in a list of the first occurrence of the specified element, or -1 if the list does not contain specified element.
lastIndexOf(Object o)  It returns the index in a list of the last occurrence of the specified element, or -1 if the list does not contain specified element.
Iterator iterator()  It returns an iterator over the elements in this list in a proper sequence.
Object[] toArray() This method is used to returns an array containing all of the elements in this list in a proper sequence.
boolean remove(Object o) It removes the first occurrence of the specified element in a list.
boolean removeFirstOccurrence(Object o) It removes the first occurrence of the specified element in a list (when traversing the list from head to tail).
removeLast​() This method removes and returns the last element from this list.
 boolean removeLastOccurrence(Object o) It removes the last occurrence of the specified element in a list (when traversing the list from head to tail).

Java LinkedList Example of Addition, removing, iteration

In this program add() method is used to add an element in LinkedList. Here LinkedList object lList is invoked add() method to add values into the list. Here remove() is used to remove an element from the specified placed or element.  ListIterator class is used to display elements of the list.
import java.util.LinkedList;
import java.util.ListIterator;
public class LinkedListAddRemoveIterateExample
{
   public static void main(String[] args)
    {
        //Create linked list
        LinkedList<String> lList = new LinkedList<>();
        //Add elements to Linked List
        lList.add("Ravi");
        lList.add("Harry");
        lList.add("Shami");
        lList.add("Cindy");
        lList.add("Sachin");
        lList.add("Salim");
        lList.add("Virat");
        System.out.println("\nPrint the Linked list elements:");
        System.out.println(lList);
        
        //Add elements at a specified position
        lList.add(3, "Alam");
        lList.add(6, "Binni");
        System.out.println("\nAfter adding at specified Postion:"); 
        System.out.println(lList);
        
        //Remove element from the linked list
        lList.remove("Cindy");    
        lList.remove(4);      
        System.out.println("\nPrint After removing the elements:");  
        System.out.println(lList);
        
        //Iterate
        ListIterator<String> itrator = lList.listIterator();
        System.out.println("\nPrint Using ListIterato:"); 
        while (itrator.hasNext()) {
            System.out.println(itrator.next());
        }
    }
}

Output:
Print the Linked list elements:
[Ravi, Harry, Shami, Cindy, Sachin, Salim, Virat]

After adding at specified Position:
[Ravi, Harry, Shami, Alam, Cindy, Sachin, Binni, Salim, Virat]

Print After removing the elements:
[Ravi, Harry, Shami, Alam, Binni, Salim, Virat]

Print Using ListIterato:
Ravi
Harry
Shami
Alam
Binni
Salim
Virat

Another Example of Linked List

import java.util.*; 
class Student { 
    // Instance variables
    int roll; 
    String name,address,section; 
    // Constructor
    public Student(int roll, String name, String address, String section) { 
        this.roll = roll; 
        this.name = name; 
        this.address = address; 
        this.section = section; 
      
    } 
public class LinkedListStudent { 
    public static void main(String[] args) { 
        //Creating LinkedList of Students 
        List<Student> linkedList=new LinkedList<Student>(); 
        //Creating Students Object 
        Student b1=new Student(1,"Ravi Kumar","Delhi","A"); 
        Student b2=new Student(2,"Salim Anwar","Kolkata","B"); 
        Student b3=new Student(3,"Virat Kholi","London","C"); 
        //Adding Students to LinkedList 
        linkedList.add(b1); 
        linkedList.add(b2); 
        linkedList.add(b3); 
        //Traversing LinkedList 
        System.out.println("Roll"+ "\t" + "Name" + "\t\t" + "Address" + "\t\t" + "Section");
        System.out.println("===================================================");
        for(Student b:linkedList){ 
            System.out.println(b.roll+"\t"+b.name+"\t"+b.address+"\t\t"+b.section); 
        } 
    } 

Output:
Roll         Name                    Address                               Section
==============================================
1              Ravi Kumar         Delhi                      A
2              Salim Anwar       Kolkata                   B
3              Virat Kholi           London                  C

Convert between Array and Linked List

In this program, a String array converted to LinkedList with  LinkedList ll = new LinkedList(Arrays.asList(name));

import java.util.*;

public class ArrayToLinkedList {

    public static void main(String[] args) {

        // Initialize array with Names
        String[] name = new String[] { "Amar", "Vicky", "Kamal", "Jamal", "Mahesh" };

        // Convert given array to LinkedList
        LinkedList ll = new LinkedList(Arrays.asList(name));

        // Iterate over each element in LinkedList.
        Iterator iterator = ll.iterator();
        while (iterator.hasNext()) {
            // Print element to console
            System.out.println((String) iterator.next());
        }
    }
}

Output
Amar
Vicky
Kamal
Jamal
Mahesh

More Program

ArrayList in Java

Array in Java