Wednesday, 10 December 2014

Java : Collection Framework : Vector (Add User defined Object)

Employee.java
public class Employee
{

    private String name;
    private int    age;
    private int    salary;

    public Employee( String name, int age, int salary )
    {
        super();
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public String getName()
    {
        return name;
    }

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

    public int getAge()
    {
        return age;
    }

    public void setAge( int age )
    {
        this.age = age;
    }

    public int getSalary()
    {
        return salary;
    }

    public void setSalary( int salary )
    {
        this.salary = salary;
    }

    @Override
    public String toString()
    {
        return "Employee [name=" + name + ", age=" + age + ", salary=" + salary
                + "]";
    }

}

VectorExample.java
import java.util.Vector;
/*
 * Storing user-defined class objects.
 */
public class VectorExample
{
    public static void main( String[] args )
    {
        Vector<Employee> vector = new Vector<Employee>();
        
        Employee john = new Employee("John", 32, 40000);
        Employee david = new Employee("David", 42, 80000);
        Employee peter = new Employee("Peter", 52, 150000);


        vector.add(john);
        vector.add(david);
        vector.add(peter);
        

        System.out.println("vector  : " + vector);
        System.out.println("----------------------------------------\n");
        
        /*
         * Using for each loop getting each employee object from the vector
         */
        for( Employee employee : vector )
        {
            System.out.println("Name : "+employee.getName());
            System.out.println("Age :"+employee.getAge());
            System.out.println("Salary :"+employee.getSalary());
            System.out.println("----------------------------------------");
        }


    }
}

Output
vector  : [Employee [name=John, age=32, salary=40000], Employee [name=David, age=42, salary=80000], Employee [name=Peter, age=52, salary=150000]]
----------------------------------------

Name : John
Age :32
Salary :40000
----------------------------------------
Name : David
Age :42
Salary :80000
----------------------------------------
Name : Peter
Age :52
Salary :150000
----------------------------------------


To Download VectorDemoUserDefinedObject Project Click the below link
https://sites.google.com/site/javaee4321/java-collections/VectorDemoUserDefinedObject.zip?attredirects=0&d=1

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • No comments:

    Post a Comment