java:循环两个布尔值(假,真)
这是一个文体问题。我想用一个设置为false的变量循环两次,然后设置为true。以下哪项更清晰:on
A)
for (final boolean on : new boolean[] { false, true} )
{
doStuffBasedOnABooleanFlag(on);
}
B)
for (int i = 0; i < 2; ++i)
{
final boolean on = (i == 1);
doStuffBasedOnABooleanFlag(on);
}
C) 其他内容
编辑:墨菲的意外解释定律开始发挥作用......我最初看到的用例是这样的,而不是doStuffBasedOnABooleanFlag:
for (final boolean on : new boolean[] { false, true} )
{
JButton button = on ? onButton : offButton;
button.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent event) {
doStuffLaterBasedOnABooleanFlag(on);
}
}
}
但我想我喜欢Brendan的答案,我只是将循环内容重构为一个单独的方法:
doStuffBasedOnABooleanFlag(false);
doStuffBasedOnABooleanFlag(true);
...
private void doStuffBasedOnABooleanFlag(final boolean on)
{
JButton button = on ? onButton : offButton;
button.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent event) {
doStuffLaterBasedOnABooleanFlag(on);
}
}
}