java中Vector的使用

2024年10月31日 17:32
有2个网友回答
网友(1):

//建立一个学生类
public class Student
{
public Student(String name,int num,String s_class)
{
this.name =name;
this.num =num ;
this.s_class =s_class ;
}
private String name = null;
private int num = 0;
private String s_class = null;
//获得信息
public String getName()
{
return name;
}
public int getNum()
{
return num;
}
public String getSClass()
{
return s_class ;
}

//重写toString
public String toString()
{
return "姓名:"+name+" 学号:"+num+" 班级: "+s_class;
}
}
Vector students = new Vector();//建立一个学生类的集合
//创建学生对象
Student one = new Student("飞飞",1,"3年级8三班");
//添加进集合
students.addElement(one);
//。。。。。。就像这样想添加多少都行。

//获取元素,循环取出
for(int i = 0;i{
Student a = students.elementAt(i);
System.out.println(a);//这样就把集合中的所有东西都打印出来了。
}

//至于Enumeration 我没这么用

网友(2):

import java.util.Vector;

public class Test {

public static void main(String[] args) {

Vector vector = new Vector();

Student stu1 = new Student("Zhang San", "001", 1);
Student stu2 = new Student("Li Si", "003", 2);
Student stu3 = new Student("Wang wu", "007", 3);

vector.add(stu1);
vector.add(stu2);
vector.add(stu3);

for(Student stu: vector){
System.out.println(stu.toString());
}

}
}

class Student{
private String name;
private String sno;
private int grade;

public Student(String name, String sno, int grade){
this.name = name;
this.sno = sno;
this.grade = grade;
}

public String toString(){
return name +": " + name + ", sno: " + sno +", Grade: " + grade;
}
}
---------------------------
Zhang San: Zhang San, sno: 001, Grade: 1
Li Si: Li Si, sno: 003, Grade: 2
Wang wu: Wang wu, sno: 007, Grade: 3

列表把vectore里面的对象放到列表中,插入值需要vectore.add(object);,修改:根据索引去更新student对象;删除:从vectore里面删除;浏览:迭代取vectore; 统计人数:返回vectore。size()