2011-12-22 88 views
8

所以現在我有一個包含一段代碼,看起來像這樣的程序......如何通過對象數組列表迭代

Criteria crit = session.createCriteria(Product.class); 
ProjectionList projList = Projections.projectionList(); 
projList.add(Projections.max("price")); 
projList.add(Projections.min("price")); 
projList.add(Projections.countDistinct("description")); 
crit.setProjection(projList); 
List results = crit.list(); 

我想要遍歷results.So預先感謝您的任何提供的幫助/建議。

+0

如果這是schoolwork標記它。否則,列表 results = crit.list();然後用於(Product p:results){} – Erik 2011-12-22 07:47:52

回答

9

在這種情況下,你將有一個列表,其元素我是以下數組: [maxPrice,minPrice,count]。

.... 
List<Object[]> results = crit.list(); 

for (Object[] result : results) { 
    Integer maxPrice = (Integer)result[0]; 
    Integer minPrice = (Integer)result[1]; 
    Long count = (Long)result[2]; 
} 
5

你可以在列表和每個但目前的代碼中使用泛型,你可以做以下迭代

for(int i = 0 ; i < results.size() ; i++){ 
Foo foo = (Foo) results.get(i); 

} 

或者更好的去可讀for-each循環

for(Foo foo: listOfFoos){ 
    // access foo here 
} 
+0

或者,如果您想稍微更現代些,可以使用迭代器? like(Iterator pi = results.iterator(); pi.hasNext();){Product p = pi.next();} – Erik 2011-12-22 08:23:21

+0

是的,但這個解決方案是舊派和低科技!誰不可能喜歡它? – gonzobrains 2014-03-30 01:20:42

+0

@gonzo是絕對非常舊的答案,已更新 – 2014-03-30 01:22:11

2

你可能做這樣的事情:

for (Object result : results) { 
    // process each result 
}