Type safety: Unchecked cast from Object to ArrayList

后端 未结 5 696
情深已故
情深已故 2020-12-09 08:36

Here is a part of a program that sends an ArrayList from a server to a client. I want to remove the warning about the last line in this code:

Client code:

         


        
5条回答
  •  囚心锁ツ
    2020-12-09 08:51

    I was running into a similar problem as OP and found a good solution with a combination of comment from @VGR and Java 1.8 method for Arrays.

    I will provide my answer in terms of OP's question, so it is generic and hopefully helps others:

    1. Instead of returning a collection (list), return an array from the server. Covert collection to an array using the following on the server side code:

      myVariableList.toArray(new MyVariable[0]);

      If performance is an issue with above, following could be used, so that array does not need to be resized:

      myVariableList.toArray(myVariableList.size());

    2. On client side convert array of object, to an array of MyVariable class.

      This is specific to JAVA 8.

      MyVariable[] myVarArr = Arrays.stream(ois.readObject()).toArray(MyVariable[]::new);

    3. Then, finally convert Array to a Collection (list).

      List myList = Arrays.asList(myVarArr);

    Thanks.

提交回复
热议问题