Why Java OutputStream.write() Takes Integer but Writes Bytes

后端 未结 5 716
被撕碎了的回忆
被撕碎了的回忆 2020-12-05 07:01

I am writing an OutputStream, just noticed this in the OutputStream interface,

   public abstract void write(int b) throws IOException;

Thi

5条回答
  •  广开言路
    2020-12-05 07:13

    Actually I've been working with bytes a bit lately and they can be annoying. They up-convert to ints at the slightest provocation and there is no designation to turn a number into a byte--for instance, 8l will give you a long value 8, but for byte you have to say (byte)8

    On top of that, they will (pretty much) always be stored internally as ints unless you are using an array (and maybe even then.. not sure).

    I think they just pretty much assume that the only reason to use a byte is i/o where you actually need 8 bits, but internally they expect you to always use ints.

    By the way, a byte can perform worse since it always has to be masked...

    At least I remember reading that years ago, could have changed by now.

    As an example answer for your specific question, if a function (f) took a byte, and you had two bytes (b1 and b2), then:

    f(b1 & b2)
    

    wouldn't work, because b1 & b2 would be up-converted to an int, and the int couldn't be down-converted automatically (loss of precision). So you would have to code:

    f( (byte)(b1 & b2) )
    

    Which would get irritating.

    And don't bother asking WHY b1 & b2 up-converts--I've been cussing at that a bit lately myself!

提交回复
热议问题