我有一个枚举,如下面的程序
所示public class Test {
public static void main(String args[]) {
Vector v = new Vector();
v.add("Three");
v.add("Four");
v.add("One");
v.add("Two");
Enumeration e = v.elements();
load(e) ; // **Passing the Enumeration .**
}
}
还有学生对象
public Student
{
String one ;
String two ;
String three ;
String four ;
}
我需要将此Enumeration传递给另一种方法,如下所示
private Data load(Enumeration rs)
{
Student stud = new Student();
while(rs.hasMoreElements())
{
// Is it possible to set the Values for the Student Object with appropiate values I mean as shown below
stud.one = One Value of Vector here
stud.two = Two Value of Vector here
stud.three = Three Value of Vector here
stud.four = Four Value of Vector here
}
}
请分享您的想法。 谢谢
答案 0 :(得分:2)
不确定。您可以使用elementAt
方法documented here来获取所需的值。您是否有使用Vector的具体原因?一些List
实现可能会更好。
答案 1 :(得分:0)
枚举不具有“第一个值”,“第二个值”等的概念。它们只具有当前值。你可以通过各种方式解决这个问题:
简单的方法 - 将其转换为更易于使用的内容,例如List
。
List<String> inputs = Collections.list(rs);
stud.one = inputs.get(0);
stud.two = inputs.get(1);
// etc.
自己跟踪位置。
for(int i = 0; i <= 4 && rs.hasNext(); ++i) {
// Could use a switch statement here
if(i == 0) {
stud.one = rs.nextElement();
} else if(i == 1) {
stud.two = rs.nextElement();
} else {
// etc.
}
}
由于以下原因,我真的不推荐这两种方法:
如果您希望您的参数按特定顺序排列,请以这种方式传递它们。它更容易维护(也适合其他人阅读)。
void example(String one, String two, String three, String four) {
Student student = new Student();
student.one = one;
student.two = two;
// etc.
}
您根本不应该使用Enumeration
,因为自Java 1.2以来它已被Iterator
和Iterable
替换。请参阅ArrayList和Collection。