简体   繁体   English

如何将java.lang.Number []转换为java.lang.Byte []?

[英]How can I cast java.lang.Number[] to java.lang.Byte[]?

I'm playing around with the Number wrappers of Java and I got the following error when I tried to cast a Number[] to Byte[]: 我在玩Java的数字包装器,尝试将Number []转换为Byte []时遇到以下错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    Cannot cast from Number[] to byte[]
    Type mismatch: cannot convert from byte[] to Byte[]

The code it breaks on is: Byte[] coordinates; 它破坏的代码是:字节[]坐标;

ByteVector(Number... coordinates) {
    super(coordinates);
    this.coordinates = (Byte[])coordinates;
}

How can I write this so that I can input an array of any kind of Number and cast it to an array of Byte? 如何编写此代码,以便可以输入任何类型的Number数组并将其转换为Byte数组?

The constructor is called with new ByteVector(1,2); 构造函数用new ByteVector(1,2);调用new ByteVector(1,2); , so ,所以

You cannot cast arrays for a simple reason: It is not safe. 您不能因为以下简单原因而转换数组:这是不安全的。 Example

Number[] numbers = new Number[10];
numbers[0] = new Byte(10);
numbers[1] = new Byte(11);
Byte[] bytes = (Byte[]) numbers;
numbers[2] = new Double(0);

So if this were allowed, there would now be a Double in the Byte[] - can't happen! 因此,如果允许这样做,则Byte []中将存在Double-无法发生! And this is actually true the other way too: 相反,这实际上也是正确的:

Byte[] numbers = new Byte[10];
numbers[0] = new Byte(10);
numbers[1] = new Byte(11);
Number[] bytesNumbers = (Number[]) numbers; // upcast - still not safe!
bytesNumbers[2] = new Double(0);

Number是可Serializable ,因此您可以简单地序列化数组。

You can use Java 8 Stream API to iterate over the array, convert each number to byte and collect to array: 您可以使用Java 8 Stream API遍历数组,将每个数字转换为字节并收集到数组:

this.coordinates = stream(numbers)
    .map(Number::byteValue)
    .toArray(Byte[]::new);

stream method is staticly imported java.util.Arrays.stream . stream方法是静态导入的java.util.Arrays.stream

Note that you might lose precision here. 请注意,此处可能会失去精度。 For example if numbers contains 12345 it will be converted to 57 . 例如,如果numbers包含12345 ,它将转换为57 Four doubles and floats, all decimal parts will be lost. 四双和浮点数,所有小数部分将丢失。

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

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