Is there a post-assignment operator for a boolean?

后端 未结 3 1108
暗喜
暗喜 2021-01-29 16:31

Hi is something like this possible in Java?

boolean flag = true;
if(flag) return flag = false; // return true and assign false to flag afterwards
3条回答
  •  天命终不由人
    2021-01-29 16:59

    Have a look at java.util.concurrent.AtomicBoolean. I haven't tried this, but it might give the behavior you're asking about:

    AtomicBoolean flag = new AtomicBoolean(true);
    System.out.println("First, I'm " + flag.get());
    Boolean was = flag.getAndSet(false);
    System.out.println("I was " + was + " but now I'm " +
        Flag.get());
    

提交回复
热议问题