Type safety: Unchecked cast from Object to ArrayList

后端 未结 5 749
情深已故
情深已故 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 09:00

    Try this

    Object obj = ois.readObject();
    // Check it's an ArrayList
    if (obj instanceof ArrayList) {
      // Get the List.
      ArrayList al = (ArrayList) obj;
      if (al.size() > 0) {
        // Iterate.
        for (int i = 0; i < al.size(); i++) {
          // Still not enough for a type.
          Object o = al.get(i);
          if (o instanceof MyVariable) {
            // Here we go!
            MyVariable v = (MyVariable) o;
            // use v.
          }
        }
      }
    }
    

提交回复
热议问题