2012-08-13 68 views
0

我傳遞了兩個系列的數據(冒號sperated :)一種方法,並期望將我的自定義類CountryDTO爲什麼在這種情況下數據沒有被設置到List對象中?

內設置這是我CountryDTO類

public class CountryDTO { 

    public CountryDTO(String a , String b , String c) 
    { 

    } 
public String value1; 
public String value2; 
public String value3; 

// setters and getters 

} 



This is my Main class 

public class Test { 

    public static void main(String args[]) throws Exception { 

     Test test = new Test(); 
     List list = (List) test.extract("IND,US,UK : WI,PAK,AUS"); 

     Iterator itr = list.iterator(); 

     while (itr.hasNext()) { 
      CountryDTO ind = (CountryDTO) itr.next(); 
      System.out.println(ind.getValue1()); 
     } 
    } 

    public List<CountryDTO> extract(final String v) throws Exception { 
     String[] values = v.split(":"); 
     List<CountryDTO> l = new ArrayList<CountryDTO>(); 
     for (String s : values) { 
      String[] vs = s.split(","); 
      l.add(new CountryDTO(vs[0], vs[1], vs[2])); 
     } 
     return l; 
    } 
} 

發生了什麼是空的是,我得到的輸出(CountryDTO沒有被設置)

誰能幫我

回答

3

很抱歉,您的DTO不正確。我想應該是這樣的:

public class CountryDTO { 

    private final String value1; 
    private final String value2; 
    private final String value3; 

    public CountryDTO(String a , String b , String c) { 
     this.value1 = ((a != null) ? a : ""); 
     this.value2 = ((b != null) ? b : ""); 
     this.value3 = ((c != null) ? c : ""); 
    } 

    // just getters; no setters 

} 

我不能到別的什麼,你的代碼可能是做錯了說話,但是這肯定是關閉基地。

+0

是的,這個工作,非常感謝。 – Pawan 2012-08-13 10:17:42

+0

接受答案,如果它的工作。 – duffymo 2012-08-13 10:18:09

3

因爲在CountryDto的構造函數中你從來沒有設置過value1,也沒有其他的值,所以它們會保持null

+1

+1我建議你讓你的領域'最後',以確保他們已被正確設置在構造函數。 – 2012-08-13 10:16:31

+0

我沒有得到你,請你告訴我,如果它的聲明最終或最後不同,最後會有什麼區別?提前致謝 ?? – Pawan 2012-08-13 10:40:03

+0

如果使用final,那麼編譯器會警告字段值未設置。 – kgautron 2012-08-13 11:18:59

相關問題