java向量类_Java中的向量类

向量是一个包含异构对象的集合,该对象可以容纳不同类类型的对象,然后将每个对象类型转换为其原始类。向量是同步的,因为多个线程可以同时处理向量,这会使向量变慢。Vector V = new Vector ();

V.add(new Student('100','ramesh'));

V.add(new Company('101','Airtel'));

在此,向量V包含两个不同类的学生和对象的对象。

我们还可以在vector中添加整数,浮点或字符串类型的值作为对象。这些值不需要强制转换。

向量的优点向量可以容纳不同类的对象。

向量是同步的。

向量的缺点

向量慢

让我们使用以下示例更清楚地了解vector:package logicProgramming;

import java.util.Vector;

//学生类

class Student

{

//类的数据成员

private int rollno;

private String name;

private String schoolCode;

//构造函数

public Student(int rollno,String name,String schoolcode)

{

this.rollno=rollno;

this.name=name;

this.schoolCode=schoolcode;

}

//putStudent()打印学生对象的值

public void putStudent()

{

System.out.println("RollNo :"+this.rollno+"\nName :"+this.rollno+"\nSchoolCode :"+this.schoolCode);

}

}

//代表员工的类

class CompanyEmployee

{

//该类的数据成员

public int id;

public String name;

public long salary;

//构造函数

public CompanyEmployee(int id,String name,long salary)

{

this.id=id;

this.name=name;

this.salary=salary;

}

//putEmployee()打印出雇员对象的值

public void putEmployee()

{

System.out.println("Id :"+this.id+"\nName :"+this.name+"\nSalary :"+this.salary);

}

}

//主类

public class ExVector {

public static void main(String[] args) {

Vector V=new Vector(); //持有对象的矢量类

V.add(new CompanyEmployee(100,"Harendra Chekkur",34000)); //将CompanyEmployee对象添加到Vector-

V.add(new Student(10,"Madhav Singh","CB2025"));  //将Student对象添加到Vector-

V.add(new Integer(70));    //将整数作为对象添加到Vector-

V.add(new String("Testing Vectors")); 将String作为对象添加到Vector-

V.add(new Float(57.4)); 将员工作为对象添加到Vector-

//迭代向量以打印对象

for(Object O:V)

{

/* as Vector holds hetrogeneous data objects thus we have to cast the object to it's type

in order to do this we are using getName() function which gets the name of the class of the given object

and compares it with the given class , if it's matches than typecast the object to that class */

if(O.getClass().getName().equals("logicProgramming.CompanyEmployee"))

{

System.out.println();

((CompanyEmployee)O).putEmployee();

}

else if(O.getClass().getName().equals("logicProgramming.Student"))

{

System.out.println();

((Student)O).putStudent();

}

//如果找不到匹配项,我们将只打印对象

else

{

System.out.println();

System.out.println(O);

}

}

}

}

输出结果Id :100

Name :Harendra Chekkur

Salary :34000

RollNo :10

Name :10

SchoolCode :CB2025

70

Testing Vectors

57.4

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值