Hibernate Validator iterator.hasNext()不起作用

时间:2015-05-09 17:04:37

标签: java hibernate validation

我使用以下代码获得无限循环(hasNext()似乎总是如此)

 private final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
 private final Validator validator = factory.getValidator();
 Set<ConstraintViolation<SomeRequest>> reqErrors = validator.validate(request);

 StringBuilder sb = new StringBuilder();
 while(reqErrors.iterator().hasNext()){
       sb.append(reqErrors.iterator().next().getMessage() + "\n");
 }

 errors = sb.toString();

这很好用:

 for(int i = 0; i < reqErrors.size(); i++){
      sb.append(reqErrors.iterator().next().getMessage() + "\n");
 }

我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

这是因为你正在调用(创建)迭代器两次!!

只需在顶部制作一次并使用它。

public class Test {
int x;
public Test(int a){
 x = a;
}
public void display(){
 System.out.println(x);
}
public static void main(String args[]){
    Test firstInstance = new Test(5);
    Test secondInstance = new Test(5);
    if(firstInstance == secondInstance)
        System.out.println("same");
    else
    {
        System.out.println("firstInstance"+firstInstance);
        System.out.println("secondInstance"+secondInstance);
    }
}