简体   繁体   English

使用错误类型的数据创建的强类型列表

[英]Strongly typed List created with wrongly typed data

I have a strongly typed List Arraylist<Byte> and a developer was trying to add primitive byte data, but the result was completely unexpected. 我有一个类型强的List Arraylist<Byte>并且开发人员试图添加原始字节数据,但是结果完全出乎意料。 A byte[] was added to this list; 一个byte[]已添加到此列表; how is this even possible? 这怎么可能? Here is a short example that demonstrates the issue in Java 7 这是一个简短的示例,演示了Java 7中的问题

public static void main(String[] args) {
    ArrayList<Byte> wrappedBytes;
    byte[] primitiveBytes = new byte[] { (byte) 0x01, (byte) 0x02, (byte) 0x03 };

    wrappedBytes = new ArrayList(Arrays.asList(primitiveBytes));

    Object value1 = wrappedBytes.get(0);
    System.out.println(value1.getClass().getSimpleName());
}

The system says the first value is a byte[] but the list should only contain Byte values. 系统说第一个值是一个byte[]但是列表中应该只包含Byte值。

You created a raw ArrayList , then assigned it to an ArrayList<Byte> . 您创建了一个原始ArrayList ,然后将其分配给ArrayList<Byte> You should have received a warning when you compiled this code about an unchecked assignment, and a warning about calling a raw ArrayList constructor given the typed return from Arrays.asList . 编译此代码时,有关未检查的分配的信息应该收到警告,如果给出了Arrays.asList的类型化返回, Arrays.asList应该收到有关调用原始ArrayList构造函数的警告。

Because of this, you wind up creating a List<byte[]> , creating a raw ArrayList with it, and assigning it to an ArrayList<Byte> . 因此,您最终创建了一个List<byte[]> ,并使用它创建了一个原始ArrayList ,并将其分配给ArrayList<Byte> This only fails to create a ClassCastException because you assigned the return of get(0) to an Object . 这只会创建ClassCastException失败,因为您将get(0)的返回值分配给了Object

The reason it's a List<byte[]> is that a List<byte> isn't possible, because primitive types aren't allowed as generic type parameters, and Arrays.asList(T... a) is a generic method. 之所以是List<byte[]>的原因是不可能使用List<byte> ,因为不允许将原始类型用作通用类型参数,而Arrays.asList(T... a)是通用方法。 The only inference is List<byte[]> . 唯一的推断是List<byte[]>

Arrays.asList expects an array of objects (T... obj) as its arguments. Arrays.asList需要对象数组(T ... obj)作为其参数。 The only object you have here is the byte[], hence you get List<byte[]> . 您在这里拥有的唯一对象是byte [],因此得到List<byte[]>

Try 尝试

Byte[] primitiveBytes = new Byte[]{...};

To complete, this 要完成,这

wrappedBytes = new ArrayList<>(Arrays.asList(primitiveBytes));

would fail when compiled with a byte[] and has no warning when compiled with Byte[]. 使用byte []编译时将失败,而使用Byte []编译时则没有警告。

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

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