2013-10-24 50 views
0

我用一個列表來檢索bean類對象的字段的值,在檢查表看起來是如何瀏覽嵌套數組列表?

resultList=ArrayList<E> 
[0]=UserDetails 
firstname=xxxxxx 
lastname=xxxxxx 
username=xxxxxx 
[1]=TaxDetails 
earnings=xxxxxx 
savings=xxxxxxx 
a/c no=xxxxxx 
[2]=null; 
[3]=null; 

現在我的問題是我怎麼可以檢索類字段的值,上通過使用 resultList.get(i)獲取值,我得到UserDetails,TaxDetails這不是我的要求。我如何導航進一步獲取其領域?請幫助!

+0

whta貴'resultList'包含? UserDetails或TaxDetails? –

回答

0

迭代這樣

for (UserDetails object : list) { 

} 

for (int i=0;i<list.size();i++) { 
     UserDetails object = list.get(i);  
    } 
0

試試這個

String firstname = "",lastname="",username="",earnings="",savings="",ac=""; 
if(i==0) 
{ 
    firstname = resultList.get(i).firstname; 
    lastname = resultList.get(i). lastname; 
    username = resultList.get(i). username; 
} 
else if(i==1) 
{ 
    earnings = resultList.get(i). earnings; 
    savings = resultList.get(i). savings; 
    ac = resultList.get(i).acno; 

} 
0

你需要轉換到相關Object才能看到它的成員變量。

一個骯髒的方式也只是做UserDetails user = (UserDetails)resultList.get(0);

但是,這是假設你知道UserDetails對象是在位置0,所以沒有最好的做法。

所以,你會想要做這樣的事情(如果你是通過列表迭代),它在做演員之前檢查對象存在的類型:

for (Object anObject : resultList){ 
    if (anObject instanceof UserDetails){ 
     UserDetails user = (UserDetails)anObject; 
     String firstname = user.firstname; 
    }else if (anObject instanceof TaxDetails){ 
     TaxDetails tax = (TaxDetails)anObject; 
     String earnings = tax.earnings; 
    } 
} 

當然,如果你是剛剛訪問一個值,而不是迭代你需要做的:

Object anObject = resultList.get(0); 

,然後執行instanceof比較和投在上面的循環。

+0

非常感謝,很好的解釋! –

0

我認爲你的列表有不同類型的元素,像UserDetails,TaxDetails?。第一印象是我不認爲將不同的元素保存在同一個集合對象中是個好主意。

爲了解決目前的問題

for (Object obj : resultList) { 
     if (obj instanceof UserDetails) { 
      UserDetails userDetails = (UserDetails)obj; 
      String firstname = userDetails.getFirstName(); 
      ... 
     } else if (obj instanceof UserDetails) { 
     ..... 
     } 
    } 

我希望它能幫助

+0

感謝它的工作! –

+0

歡迎:),並可以請你接受它作爲答案:) – Jayasagar

+0

我已經有。 :) –