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
热门推荐
9 带清的简短祝福语
10 祝福语写给自己的简短
11 高考祝福语简短10字
12 周末祝福语简短的英语
13 拜年啦祝福语大全简短
14 祝福语简短古诗词
15 表达朋友的祝福语简短
16 入学祝福语简短走心
17 18岁简短祝福语经典
18 想念老公生日祝福语简短