2012-03-21 88 views
0

我有一个枚举如下面方案中所示的java:从枚举映射值到对象

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 .** 

    } 

} 

还有一个Student对象

public Student 
{ 
String one ; 
String two ; 
String three ; 
String four ; 
} 

我需要通过此枚举为另一种方法,如下所示

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 

} 
} 

请在此分享你的想法。 谢谢

+1

为什么使用'Vector'和'Enumeration'? ArrayList和Collection更容易处理。 – 2012-03-21 14:46:33

回答

2

当然。您可以使用elementAt方法,documented here来获得您想要的值。你有使用Vector的具体原因吗?一些List实现可能会更好。

0

枚举不具有“第一值”,“第二值”等概念,它们只是具有当前值。你可以解决这个以不同的方式:

  1. 最简单的办法 - 它转换成一些更容易使用,就像一个List

    List<String> inputs = Collections.list(rs); 
    stud.one = inputs.get(0); 
    stud.two = inputs.get(1); 
    // etc. 
    
  2. 自己跟踪位置。

    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替换IteratorIterable。见ArrayListCollection