繁体   English   中英

Sonarlint 哨兵值假阳性

[英]Sonarlint sentinel value fake positive

我有下一个代码片段,其中 sonarlint 工具说我的 boolean 变量 sentinel 始终评估为 true,而sentinel = true这是一个无用的声明。

import static java.lang.System.*;

public class Sentinel {

    private static final int[] array = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    public static void main(String[] args) {
        boolean sentinel = false;
        int counter = 0;
        while (!sentinel) {
            out.println( "Counter: " + counter);
            out.println( "Array index: " + array[counter] );
            counter++;
            if ( counter == array.length - 1 ) {
                out.println( "End of the array reached" );
                sentinel = true;
                out.println( "Breaking..." );
                break;
            }
        }
    }
}

sonarlint analisys 可能有什么问题? 代码完美编译并按预期运行。

问候。

更新:

@kkk 提供了两个有价值的答案。 见下文,但我在这里放了我更喜欢的一个:

import java.util.concurrent.atomic.AtomicBoolean;

import static java.lang.System.*;

public class Sentinel {

    private static final int[] array = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    public static void main(String[] args) {
        AtomicBoolean sentinel = new AtomicBoolean(false);
        int counter = 0;
        while ( !sentinel.get() ) {
            out.println( "Counter: " + counter);
            out.println( "Array index: " + array[counter] );
            counter++;
            if ( counter == array.length - 1 ) {
                out.println( "Counter limit reached" );
                sentinel.set( true );
                out.println( "Breaking..." );
                break;
            }
        }
    }
}

sentinel = true; while (!sentinel)从未见过。 那是因为 break 语句。

话虽如此,您的代码使用for循环要简单得多。 你的while只是让它变得复杂。

for(int counter = 0; counter < array.length; counter++) {
    out.println("Counter: " + counter);
    out.println("Array index: " + array[counter]);
    if (counter == array.length - 1) {
        out.println("End of the array reached");
        out.println("Breaking...");
    }
}

或者,更好的是,在循环之后执行counter == array.length - 1动作

for(int counter = 0; counter < array.length; counter++) {
    out.println("Counter: " + counter);
    out.println("Array index: " + array[counter]);
}
out.println("End of the array reached");
out.println("Breaking...");

制作前哨 static 或用户 AtomicBoolean,这是可见性问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM