How to use Vector collection implementation in Java environment


Vector collection is an implementation of the List interface in Java Collection Framework.
Vector is also a synchronized collection that could be used in thread safe applications.
Because of that it has slower performance than the ArrayList implementation of the List Interface.

Here is an example program for the usage of Vector collection class in Java


/*
 *How to use a Vector implementation of Java Collection Framework
 */

package vectorexample;

import java.util.Iterator;
import java.util.List;
import java.util.Vector;

/**
 *
 * @author tunatore
 */

public class VectorExample {

public static void main(String[] args) {

System.out.println("==========VECTOR EXAMPLE==========");
List<String> vectorOne = new Vector<String>();        
vectorOne.add("this is the first element for the VectorOne");
vectorOne.add("this is the second element for the VectorOne");
vectorOne.add("this is the third element for the VectorOne");

Vector<String> vectorTwo = new Vector<String>();
vectorTwo.add("this is the first element for the vectorTwo");
vectorTwo.add("this is the second element for the vectorTwo");

System.out.println("The size of the vectorOne --> " + vectorOne.size());
System.out.println("The size of the vectorTwo --> " + vectorTwo.size());

System.out.println("==========Getting the elements inside vectorTwo==========");

for (Iterator<String> it = vectorTwo.iterator(); it.hasNext();) {
String element = it.next();
System.out.println(element);
}

System.out.println("==========Testing an element existince in vectorTwo==========");
System.out.println("Exist or Not --> " + vectorTwo.contains("this is the second element for the vectorTwo"));

System.out.println("==========Removing an element using index remove(i) in vectorTwo==========");
vectorTwo.remove(1); // 1 refers to the second element in vectorTwo

System.out.println("==========Testing againg an element existince in vectorTwo==========");
System.out.println("Exist or Not --> " + vectorTwo.contains("this is the second element for the vectorTwo"));

System.out.println("==========Adding two more elements in vectorTwo==========");
vectorTwo.add("this is the second element for the vectorTwo");
vectorTwo.add("this is the third element for the vectorTwo");

System.out.println("==========Getting the first element of vectorTwo==========");
System.out.println("The first element ==> " + vectorTwo.firstElement());

System.out.println("==========Getting the last element of VectorOne==========");
System.out.println("The last element ==> " + vectorTwo.lastElement());
}
}

The Output for the program;

run:
==========VECTOR EXAMPLE==========
The size of the vectorOne –> 3
The size of the vectorTwo –> 2
==========Getting the elements inside vectorTwo==========
this is the first element for the vectorTwo
this is the second element for the vectorTwo
==========Testing an element existince in vectorTwo==========
Exist or Not –> true
==========Removing an element using index remove(i) in vectorTwo==========
==========Testing againg an element existince in vectorTwo==========
Exist or Not –> false
==========Adding two more elements in vectorTwo==========
==========Getting the first element of vectorTwo==========
The first element ==> this is the first element for the vectorTwo
==========Getting the last element of VectorOne==========
The last element ==> this is the third element for the vectorTwo
BUILD SUCCESSFUL (total time: 0 seconds)

Download Source

Advertisements

How to use Set Collection in Java (HashSet, LinkedHashSet, TreeSet)


Use the following code for understanding how HashSet, TreeSet and LinkedHashSet are used in Java development environment.

package javacollectionsetexample;

import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.TreeSet;

/**
 *
 * @author tunatore
 */
public class Main {
  /**
     * Collection is the super interface for the Set interface
     * Set is an interface
     * (public interface Set extends Collection)
     * SortedSet is a sub interface for the Set interface
     * (public interface SortedSet extends Set)
     * Implementing classes for the Set interface are:
     * AbstractSet, HashSet, LinkedHashSet, TreeSet
     * TreeSet is the only implementing class for the SortedSet interface
     */
     public static void main(String[] args) {

       Car car1 = new Car();
       Car car2 = new Car();
       Car car3 = new Car();
       Car car4 = new Car();
       Car car5 = new Car();

       car1.setName("SUBARU");
       car1.setModelYear(2000);
       car1.setMotorPower(3000);

       car2.setName("HONDA");
       car2.setModelYear(1999);
       car2.setMotorPower(2000);

       car3.setName("TOYOTA");
       car3.setModelYear(2004);
       car3.setMotorPower(1600);

       car4.setName("NISSAN");
       car4.setModelYear(2005);
       car4.setMotorPower(1200);

       car5.setName("HUNDAI");
       car5.setModelYear(2008);
       car5.setMotorPower(1400);

       System.out.println("\nTreeSet Example Starts\n");

       TreeSet<Car> carsTreeSet = new TreeSet<Car>();
       carsTreeSet.add(car1);
       carsTreeSet.add(car2);
       carsTreeSet.add(car3);
       carsTreeSet.add(car4);
       carsTreeSet.add(car5);

       //dublicate elements are not allowed in SETs
       //this statement will be ignored there will be only
       //one car5 element will be exist inside TreeSet
       carsTreeSet.add(car5);

        //Cars inside TreeSet will be sorted according to their motor power
        //Comparing objects will be done inside Car class by calling compareTo(Car carToCompare)
        //method internally from TreeSet collection class

       for (Iterator<Car> it = carsTreeSet.iterator(); it.hasNext();) {
       Car car = (Car) it.next();
       System.out.println("CAR name --> " + car.getName()
       + " Motor Power --> " + car.getMotorPower());
       }

       System.out.println("\nTreeSet DESCENDING order order\n");

      //if you need to get descending order use descending iterator

      for (Iterator<Car> it = carsTreeSet.descendingIterator(); it.hasNext();) {
      Car car = it.next();
      System.out.println("CAR name --> " + car.getName()
      + " Motor Power --> " + car.getMotorPower());
      }

       System.out.println("\nHashSet Example Starts\n");

       //HashSet Does not guarantee the order of its elements

       HashSet<Car> carHashSet = new HashSet<Car>();
       carHashSet.add(car1);
       carHashSet.add(car2);
       carHashSet.add(car3);
       carHashSet.add(car4);
       carHashSet.add(car5);
       //dublication of elements still not allowed
       carHashSet.add(car5);

      for (Iterator<Car> it = carHashSet.iterator(); it.hasNext();) {
      Car car = it.next();
      System.out.println("CAR name --> " + car.getName()
      + " Motor Power --> " + car.getMotorPower());
}

       System.out.println("\nLinkedHashSet Example Starts\n");

       //LinkedHashSet will maintain the order of Car elements
       //Car1 will be followed by car2,car3  ... car5
       //the ordering will be maintained according to the insertion order
       LinkedHashSet<Car> carLinkedHashSet = new LinkedHashSet<Car>();
       carLinkedHashSet.add(car1);
       carLinkedHashSet.add(car2);
       carLinkedHashSet.add(car3);
       carLinkedHashSet.add(car4);
       carLinkedHashSet.add(car5);

for (Iterator<Car> it = carLinkedHashSet.iterator(); it.hasNext();) {
Car car = it.next();
System.out.println("CAR name --> " + car.getName()
+ " Motor Power --> " + car.getMotorPower());
}
}
}

Car.java class



package javacollectionsetexample;

/**
*
* @author tunatore
*/

public class Car implements Comparable<Car>{

private String name;
private int motorPower;
private int modelYear;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getMotorPower() {
return motorPower;
}

public void setMotorPower(int motorPower) {
this.motorPower = motorPower;
}

public int getModelYear() {
return modelYear;
}

public void setModelYear(int modelYear) {
this.modelYear = modelYear;
}

    //this method will be used by TreeSet class
    //for sorting the car class elements according to Motor Power

public int compareTo(Car carToCompare) {

        //return zero if two objects are equal
        if (this.motorPower == carToCompare.getMotorPower() ) {
            return 0;
        } //return -1 if the current object is smaller than the object compared
        else if (this.motorPower < carToCompare.getMotorPower()) {
            return -1;
        } //return 1 if the current object is bigger than the object compared
        else {
            return 1;
        }

}

}

Sample Output of the program;

run:

TreeSet Example Starts

CAR name –> NISSAN Motor Power –> 1200
CAR name –> HUNDAI Motor Power –> 1400
CAR name –> TOYOTA Motor Power –> 1600
CAR name –> HONDA Motor Power –> 2000
CAR name –> SUBARU Motor Power –> 3000

TreeSet DESCENDING order

CAR name –> SUBARU Motor Power –> 3000
CAR name –> HONDA Motor Power –> 2000
CAR name –> TOYOTA Motor Power –> 1600
CAR name –> HUNDAI Motor Power –> 1400
CAR name –> NISSAN Motor Power –> 1200

HashSet Example Starts

CAR name –> NISSAN Motor Power –> 1200
CAR name –> TOYOTA Motor Power –> 1600
CAR name –> HONDA Motor Power –> 2000
CAR name –> HUNDAI Motor Power –> 1400
CAR name –> SUBARU Motor Power –> 3000

LinkedHashSet Example Starts

CAR name –> SUBARU Motor Power –> 3000
CAR name –> HONDA Motor Power –> 2000
CAR name –> TOYOTA Motor Power –> 1600
CAR name –> NISSAN Motor Power –> 1200
CAR name –> HUNDAI Motor Power –> 1400
BUILD SUCCESSFUL (total time: 1 second)

Exception may occurs like the following one if you do not  implement Comparable interface by Car class.

run:
Exception in thread “main” java.lang.ClassCastException: javacollectionsetexample.Car cannot be cast to java.lang.Comparable
        at java.util.TreeMap.put(TreeMap.java:542)
        at java.util.TreeSet.add(TreeSet.java:238)
        at javacollectionsetexample.Main.main(Main.java:55)
Java Result: 1


Download Source