简体   繁体   中英

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. A byte[] was added to this list; how is this even possible? Here is a short example that demonstrates the issue in 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.

You created a raw ArrayList , then assigned it to an 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 .

Because of this, you wind up creating a List<byte[]> , creating a raw ArrayList with it, and assigning it to an ArrayList<Byte> . This only fails to create a ClassCastException because you assigned the return of get(0) to an 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. The only inference is List<byte[]> .

Arrays.asList expects an array of objects (T... obj) as its arguments. The only object you have here is the byte[], hence you get 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[].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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