类型安全:未选中从Object转换到ArrayList的<&MyVariable的GT; [英] Type safety: Unchecked cast from Object to ArrayList<MyVariable>

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

问题描述

下面是发送一个ArrayList从服务器到客户端的程序的一部分。我想删除有关此code中的最后一行警告:

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:

客户端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.

我想知道为什么我有一个警告那里,如何完美地code才能有0个警告。如果有可能,我想避免使用@燮pressWarnings(未登记)。 ;)

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的&LT;&MyVariable的GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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