简体   繁体   中英

No unused variable warning using arrays in eclipse

I use Eclipse Kepler and have a java file with this code:

String[] arr = new String[] {"abc", "def"};

Eclipse now shows a warning:

The value of the local variable arr is not used

If I add one line, the warning vanishes:

String[] arr = new String[] {"abc", "def"};
arr[0] = "ghi";

Although no element of the array is read, Eclipse does not warn me about this. Is there a reason for this behaviour or is it just an Eclipse bug? (IntelliJ warns about arrays with no read access of their elements.)

Edit: I know that the array itself is used, but I want my IDE to be smart enough to check if any elements inside the array have been used, because an array is in fact a container for its elements.

It's not a bug. For the compiler, when he see arr[0] , then the value was used. Because first the program reads the content of arr[0] , then create "ghi" String, then assign it to arr[0] . In the first case, the compiler notice that the variable is not referenced, so it warns you.

There's a difference between detecting use, reads and writes to structures. Eclipse evidently only does the former (presumably because it's slightly easier) while others (such as IntelliJ) are more sophisticated and can deduce more information.

It's not a bug; they simply didn't prioritize static analysis as highly in Eclipse.

Eclipse is basically not smart enough to realise that the line of code you wrote doesn't actually have any effect on the behaviour of the program (In general this is very hard for a computer to determine). As far as it's concerned, if a local variable is not referenced after its declaration, it is unused.

In here

    String[] arr = new String[] {"abc", "def"};
    arr[0] = "ghi";  // you are writing to arr

But never read. Now both conditions are correct. arr use in the code and never read arr

Then IntelliJ IDEA will said you are not read arr here while Ecplise never show previous warning. That is not a bug. Those two are features of IntelliJ IDEA and Eclipse .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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