OOPM JAVA - Create a vector Student with their name.

 Experiment No. 9

Aim: Create a vector Student with their name. Write a program to add, remove and display students name from vector.

Objective: To make aware of dynamic growable arrays i. e. Vector class from util package in real world scenario. 

Outcome: Students used vectors successfully for dynamic increase in size of array for real world problem.

Theory:

Vector implements a dynamic array. It is similar to ArrayList, but with two differences −

  • Vector is synchronized.
  • Vector contains many legacy methods that are not part of the collections framework.

Vector proves to be very useful if you don't know the size of the array in advance or you just need one that can change sizes over the lifetime of a program.

Following is the list of constructors provided by the vector class.

Vector( )

creates a default vector, which has an initial size of 10.

Vector(int size)

creates a vector whose initial capacity is specified by size

Vector(int size, int incr)

creates a vector whose initial capacity is specified by size and whose increment is specified by incr. The increment specifies the number of elements to allocate each time that a vector is resized upward 

Vector(Collection c)

creates a vector that contains the elements of collection c.


Vector defines three protected data member:

int capacityIncreament: Contains the increment value.

int elementCount: Number of elements currently in vector stored in it.

Object elementData[]: Array that holds the vector is stored in it.

Methods of Vector class

  • addElement(Object)

Adds the specified component to the end of this vector, increasing its size by one.

  • capacity()

Returns the current capacity of this vector.

  • clone()

Returns a clone of this vector.

  • contains(Object)

Tests if the specified object is a component in this vector.

  • copyInto(Object[])

Copies the components of this vector into the specified array.

  • elementAt(int)

Returns the component at the specified index.

  • elements()

Returns an enumeration of the components of this vector.

  • ensureCapacity(int)

Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument.

  • firstElement()

Returns the first component of this vector.

  • indexOf(Object)

Searches for the first occurence of the given argument, testing for equality using the equals method.

  • indexOf(Object, int)

Searches for the first occurence of the given argument, beginning the search at index, and testing for equality using the equals method.

  • insertElementAt(Object, int)

Inserts the specified object as a component in this vector at the specified index.

  • isEmpty()

Tests if this vector has no components.

  • lastElement()

Returns the last component of the vector.

  • lastIndexOf(Object)

Returns the index of the last occurrence of the specified object in this vector.

  • lastIndexOf(Object, int)

Searches backwards for the specified object, starting from the specified index, and returns an index to it.

  • removeAllElements()

Removes all components from this vector and sets its size to zero.

  • removeElement(Object)

Removes the first occurrence of the argument from this vector.

  • removeElementAt(int)

Deletes the component at the specified index.

  • setElementAt(Object, int)

Sets the component at the specified index of this vector to be the specified object.

  • setSize(int)

Sets the size of this vector.

  • size()

Returns the number of components in this vector.

  • toString()

Returns a string representation of this vector.

  • trimToSize()

Trims the capacity of this vector to be the vector's current size.


Algorithm:

  • start
  • create an object of Vector class
  • add five student names to Vector using addElement() method of Vector class
  • select option from menu
  • if option is , then add new student name to Vector using addElement() method of Vector class
  • if option is 2, then remove specific element from Vector using removeElement() method of Vector class
  • if option is 3, then display all Vector elements using Enumeration class methods nextElement() and hasMoreElements().
  • stop 


Code : 

import java.io.*;

import java.util.Vector;

import java.util.*;

class Vector1

{

public static void main(String args[])

{

int choice=0;

DataInputStream in=new DataInputStream(System.in);

Vector v = new Vector();

String s,student;

try

{

    do

    {

        System.out.println("Select your choice:");

        System.out.println("1 - Add Student name");

        System.out.println("2 - Remove Student name");

        System.out.println("3 - View Student names");

        System.out.println("4 - Exit");

        choice=Integer.parseInt(in.readLine());

 

        switch(choice)

        {

            case 1: 

                System.out.println("Enter name of student:");

                student=in.readLine(); 

                if(v.contains(student))

                System.out.println("Student name already exists");

                else

                {

                    v.addElement(student);

                    System.out.println("Student name added");

                }

                break;

 

            case 2 : if(v.isEmpty())

                System.out.println("Students name list is empty");

                else

                {

                    System.out.println("Enter name of student:");

                    student=in.readLine(); 

                if(v.contains(student))

                {

                    v.removeElement(student);

                    System.out.println("Student name removed");

                }

                else

                System.out.println("Student name does not exist");

                }

                break;

 

            case 3 : if(v.isEmpty())

                System.out.println("Students name list is empty");

                else 

                System.out.println("Vector : "+v.toString());

                break;

            case 4 : System.exit(0);

                    break;  

        }

        System.out.println("Do you want to continue? Press y or n");

        s=in.readLine();

 

    }while(s.equals("y"));

}

catch(Exception e)

{

    System.out.println("Exception caught:"+e);

}

}

}


Output : 

Create a vector Student with their name. Write a program to add, remove and display students name from vector.


Observations and learning: 

In this experiment we introduced vector. We have also used switch case to provide various options to user.

Conclusion: 

By using this program a list is created provided with options to add, remove and view the elements in it.

 

Question of Curiosity 

1. What is a vector in Java?

Ans:- Vectors is like the dynamic array which can grow or shrink its size. Unlike array, we can store n-number of elements in it as there is no size limit. It is a part of Java Collection framework since Java 1.2. It is found in the java.utilpackage and implements the List interface, so we can use all the methods of List interface here.The java.util.Vector class implements a growable array of objects. Similar to an Array, it contains components that can be accessed using an integer index.


2. What is the Difference Between Arraylist and Vector?

 

ArrayList

Vector

1) ArrayList is not synchronized.

2) ArrayList increments 50% of current array size if the number of elements 

exceeds from its capacity.

3) ArrayList is not a legacy class. It is introduced in JDK 1.2.

4) ArrayList is fast because it is non-synchronized.

5) ArrayList uses the Iterator interface to 

traverse the elements.

1)Vector is synchronized.

2)Vector increments 100% means doubles the array size if the total number of elements exceeds than its capacity.

3)Vector is a legacy class.

4)Vector is slow because it is synchronized, i.e., in a multithreading environment, it holds the other threads in runnable or non-runnable state until current thread releases the lock of 

theobject.


3. What is the Difference Between Iterator and Listiterator?

Ans:-

1. The basic difference between Iterator and ListIterator is that both being cursor, Iterator can traverse elements in a collection only in forward direction. On the other hand, the ListIterator can traverse in both forward and backward directions.

2. Using iterator you can not add any element to a collection. But, by using ListIterator you can add elements to acollection.

3. Using Iterator, you can not remove an element in a collection where, as 

You can remove an element from a collection usingListIterator.

4. Using Iterator you can traverse all collections like Map, List, Set. But, by 

ListIteror you can traverse List implemented objectsonly.

5. You can retrieve an index of an element using Iterator. But as List is 

sequential and index-based you can retrieve an index of an element in usingListIterator.

 

4. Why Vector is a synchronized in Java?

Ans:-Vector was part of JDK 1.0; ArrayList was not. We learned that synchronization as a default meant poor performance, so it was reversed when the Java Collections API cameout.This means if one thread is working on Vector, no other thread can get a hold of it.Vector operations gives poor performance as they are thread-safe, the thread which works on Vector gets a lock on it which makes other thread wait till the lock is released.

 

5. Is a vector thread safe Java?

Ans:- Vector methods are all synchronized. So using it from multiple threads is "safe". You only need to synchronize if you need a read-evaluate-write process tobeatomic .......If the shared state is the Vector object, then you need to synchronize on the instance of your Vector, not on an instance of your own classes.

 

6. How can an ArrayList be synchronized without using Vector?

Ans:-In order to get a synchronized list from an ArrayList, we use the synchronizedList(List <T>) method in Java. The Collections.synchronizedList(List <T>) method accepts the ArrayList as an argument and returns a thread safe list.Declaration −The Collections.synchronizedList(List <T>) method is declared as follows −public static List <T> synchronizedList(List <T> list)


Comments