Question

Here's the code snippet:

    ByteBuffer buf = ByteBuffer.allocate(deleteInfo.size);
    for(int j = 0; j < deleteInfo.size; j++)
      buf.put(j,(byte)'.');

Here's the warning on the last line above:

Unnecessary cast to byte

I agree, but when I remove the cast...

  buf.put(j, '.');

... here's the error:

incompatible types; possible lossy conversion from char to byte

I realize that char is two bytes in Unicode, so surely this is the reason for the error. In this cast of char to byte, the warning has no negative implications, since all of my data is ASCII. (I tried using the actual ASCII code for '.'; same results.)

So I can safely ignore the error, but I'd like to deal with this "legitimately" and not just turn off or ignore the warning mechanism.

None of the topics that showed up on the page to submit questions appear to address the problem. Google turned up getBytes and System.getProperty("file.encoding") returns "UTF-8" without me saying I want to use that encoding, but I can't see how to apply getBytes("UTF-8") (or anything else) to buf.

How can I code to avoid the warning? Or should I just write it off as a danged-if-I-do-danged-if-I-don't Netbeans quirk?

Was it helpful?

Solution 2

It's horrible and cumbersome but you can avoid the cast with:

".".getBytes()[0]

which is actually exactly what you want. A char is actually an int in different clothing and you want the low byte of the int - which is what this does.

OTHER TIPS

You don't necessarily need to add code to get rid of the warning.

Open NetBeans and navigate to Tools -> Options -> Editor. Go to the 'Hints' tab, select java and open the 'Standard Javac Warnings' drop-down and uncheck 'Unnecessary Cast' box.

If you are using a Mac instead, then all steps are the same, except for going to Tools -> Options go to NetBeans -> Preferences.

Alternatively you can add @SuppressWarnings("cast") above the method where you are casting that stuff.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top