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