如何遍历Object数组列表

Nav*_*n A 10 java hibernate

所以现在我有一个包含一段看起来像这样的代码的程序......

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();
Run Code Online (Sandbox Code Playgroud)

我想迭代结果.所以提前感谢您提供的任何帮助/建议.

Com*_*ade 14

在这种情况下,您将拥有一个列表,其元素是以下数组:[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];
}
Run Code Online (Sandbox Code Playgroud)


Jig*_*shi 5

您可以在列表中使用Generic,但对于每个但是对于当前代码,您可以执行以下迭代

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

}
Run Code Online (Sandbox Code Playgroud)

或者更好地去寻找每个循环的可读性

for(Foo foo: listOfFoos){
  // access foo here
}
Run Code Online (Sandbox Code Playgroud)


Ted*_*opp 5

你也许可以这样做:

for (Object result : results) {
    // process each result
}
Run Code Online (Sandbox Code Playgroud)