这是从服务器向客户端发送 ArrayList 的程序的一部分。我想删除这段代码最后一行的警告:
客户端代码:
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 变量作为项目填充它。然后它将完整的列表发送给客户端。
我想知道为什么我会在那里出现警告,以及如何完美地编写代码以获得 0 个警告。如果可能的话,我想避免使用“@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.
}
}
}
}
关于java - 类型安全 : Unchecked cast from Object to ArrayList<MyVariable>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20275623/