我需要迭代保存的客户端连接(在服务器端)并向他们发送消息(就像一个人写消息一样--其他连接的人也应该看到它)。
我试过这样做:
for (PrintWriter out : connections) {
out.println(message);
out.flush();
}connections是
LinkedList connections = new LinkedList();但是对于for循环,我得到以下错误:
Type mismatch: cannot convert from element type Object to PrintWriter.有谁能帮我或者建议另一个主意怎么做吗?谢谢。
发布于 2014-11-03 11:22:46
LinkedList connections = new LinkedList();是一个原始类型,因此它知道它的元素是type对象。您需要向它添加一个泛型类型参数:
LinkedList<PrintWriter> connections = new LinkedList<>();发布于 2014-11-03 11:22:21
而不是
LinkedList connections = new LinkedList();使用
LinkedList<PrintWriter> connections = new LinkedList<PrintWriter>();。这可以确保您只能将PrintWriter放到列表中,并且当将对象从列表中取出时,编译器可以确保取出的对象是PrintWriter,并且不会再有问题了。
https://stackoverflow.com/questions/26713094
复制相似问题