2012-03-21 21 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