类型安全:从 Object 到 ArrayList<MyVariable> 的未经检查的强制转换 [英] Type safety: Unchecked cast from Object to ArrayList&lt;MyVariable&gt;

查看:59
本文介绍了类型安全:从 Object 到 ArrayList<MyVariable> 的未经检查的强制转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是从服务器向客户端发送 ArrayList 的程序的一部分.我想删除有关此代码中最后一行的警告:

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:

客户端代码:

Socket s;
(...)
// A server is sending a list from the other side of the link.
ois = new ObjectInputStream(s.getInputStream());
MyList = (ArrayList<MyVariable>) ois.readObject();

MyVariable 是一个带有一些属性的 Java 类.服务器正在创建一个 ArrayList 并用 MyVariable 变量作为项目填充它.然后将完整列表发送给客户端.

MyVariable is a Java class with some attributes. The server is creating an ArrayList and filling it with MyVariable variables as items. Then it sends the complete list to the client.

我想知道为什么我在那里有警告,以及如何完美编码以获得 0 个警告.如果可能的话,我想避免使用@SuppressWarnings(unchecked")".;)

I would like to know why do I have a warning there and how to code perfectly in order to have 0 warnings. If it is possible I would like to avoid using "@SuppressWarnings("unchecked")". ;)

谢谢,

路易斯

推荐答案

试试这个

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.
      }
    }
  }
}

这篇关于类型安全:从 Object 到 ArrayList<MyVariable> 的未经检查的强制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆