2011-12-22 89 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 
}