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

后端 未结 2 769
遇见更好的自我
遇见更好的自我 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条回答
  •  -上瘾入骨i
    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.

提交回复
热议问题