Are the method calls inside if-checks “tested” and then “reverted”?

后端 未结 2 770
遇见更好的自我
遇见更好的自我 2021-01-29 10:15

I have suddenly forgotten how method calls inside if-checks works.

Example:

if (list.next() instanceof AClass) {
    AClass thing = list.next();
}


        
相关标签:
2条回答
  • 2021-01-29 10:40

    The answer depends on the implementation of the next() method. For example, if list is an Iterator then each call to next() advances the iterator, so the two calls in your code would give a different result (assuming they don't throw an exception). The same is true if list is a Scanner. Each call to next() would produce a different output.

    On the other hand, if the next() method just returns some property of the list instance and doesn't change its state, multiple calls to it would give the same output.

    Usually methods called next() change the state of the object on which they are called, but that's just a coding convention.

    0 讨论(0)
  • 2021-01-29 10:46

    If list is an Iterator, you may need something like:

    AClass thing = null;
    Object n = list.next();
    if (n instanceof AClass) {
         thing = (AClass) n;
    }
    

    in order to call .next() just once. Two subsequent calls will return two objects, because internal position is moved one step forward on each .next() invocation. There no any kind of "reversion" occurs.

    0 讨论(0)
提交回复
热议问题