本文介绍了为什么ByteArrayOutputStream使用int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许有人可以帮助我理解,因为我觉得我错过的东西可能会对我的程序运行方式产生影响。

Maybe someone can help me understand because I feel I'm missing something that will likely have an effect on how my program runs.

我正在使用ByteArrayOutputStream 。除非我错过了一些巨大的东西,否则这个类的重点是创建一个byte []数组用于其他用途。

I'm using a ByteArrayOutputStream. Unless I've missed something huge, the point of this class is to create a byte[] array for some other use.

然而,普通写入函数BAOS取一个int而不是一个字节()。

However, the "plain" write function on BAOS takes an int not a byte (ByteArrayOutputStream.write).

根据这个()页面,在Java中,int是32位数据类型,字节是8位数据类型。

According to this(Primitive Data Types) page, in Java, an int is a 32-bit data type and a byte is an 8-bit data type.

如果我写这段代码......

If I write this code...

int i = 32;
byte b = i;

我收到有关可能需要更改的有损转换的警告......

I get a warning about possible lossy conversions requiring a change to this...

int i = 32;
byte b = (byte)i;

我对write(int)感到困惑......

I'm really confused about write(int)...

推荐答案

ByteArrayOutputStream 只是覆盖在 OutputStream 。所以真正的问题是为什么是这样声明的,当它声明的目标是将单个字节写入流时。流的实现在这里是无关紧要的。

ByteArrayOutputStream is just overriding the abstract method declared in OutputStream. So the real question is why OutputStream.write(int) is declared that way, when its stated goal is to write a single byte to the stream. The implementation of the stream is irrelevant here.

你的直觉是正确的 - 在我看来,这是一个破碎的设计。是的,它会丢失数据,正如文档中明确指出的那样:

Your intuition is correct - it's a broken bit of design, in my view. And yes, it will lose data, as is explicitly called out in the docs:

对于这个来说,这将是更明智的(在我看来) 写(字节)。唯一的缺点是你不能在没有强制转换的情况下用文字值调用它:

It would have been much more sensible (in my view) for this to be write(byte). The only downside is that you couldn't then call it with literal values without casting:

// Write a single byte 0. Works with current code, wouldn't work if the parameter
// were byte.
stream.write(0);

看起来没问题,但不是 - 因为文字0的类型是 int ,它不能隐式转换为 byte 。你必须使用:

That looks okay, but isn't - because the type of the literal 0 is int, which isn't implicitly convertible to byte. You'd have to use:

// Ugly, but would have been okay with write(byte).
stream.write((byte) 0);

对我而言,设计API的方式不是很好,但这就是我们的意思自从Java 1.0以来,它已经拥有了。不幸的是,如果没有它在整个地方发生重大变化,它现在无法修复。

For me that's not a good enough reason to design the API the way it is, but that's what we've got - and have had since Java 1.0. It can't be fixed now without it being a breaking change all over the place, unfortunately.

这篇关于为什么ByteArrayOutputStream使用int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 10:57
查看更多