如何遍历对象数组列表

13

目前,我有一个程序,其中包含一个类似于以下代码的部分...

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();

我想要迭代结果。非常感谢提供任何帮助/建议的人。


如果这是学校作业,请标记为此类。否则,List<Product> results = crit.list(); 然后 for (Product p: results) {} - Erik
3个回答

22
在这种情况下,您将拥有一个列表,其元素是以下数组:[最大价格,最小价格,计数]。
....
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
你可以在List和for each中使用Generic,但对于当前的代码,你可以按照以下方式进行迭代。
for(int i = 0 ; i < results.size() ; i++){
 Foo foo = (Foo) results.get(i);

}

或者更好的选择是使用易读的for-each循环。

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

或者如果你想要更加现代化,可以使用迭代器吗?像这样:for (Iterator<Product> pi = results.iterator(); pi.hasNext();) { Product p = pi.next();} - Erik
是的,但这个解决方案很老派和低科技!谁可能会喜欢它呢? - gonzobrains
无法将 (object[]) 对象数组转换为像 Foo 一样的对象。 - Salahin Rocky

5
您可以尝试像这样做:

您可能可以尝试以下操作:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接