2014-11-03 47 views
0

我需要遍歷已保存的客戶端連接(在服務器端)並向它們發送消息(因爲一個人寫了一條消息 - 其他連接也應該看到它)。PrintWriter和LinkedList

我想這樣做:

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. 

誰能幫助我,或建議另一個想法是如何完成它。謝謝。

+0

只是一個集合,你應該告訴它的類型,怎麼樣,你說'INT [ ]',一個整數類型的數組,類似地給LinkedList一個類型參數,例如'LinkedList ',或'LinkedList '在你的情況下 – AsSiDe 2014-11-03 11:23:30

+0

鏈表哪些類型的值 – 2014-11-03 11:24:55

回答

1
LinkedList connections = new LinkedList(); 

是一個原始類型,因此它知道它作爲Type對象的元素。你需要一個泛型類型放慢參數添加到它:

LinkedList<PrintWriter> connections = new LinkedList<>(); 
要在LinkedList的對象來存儲
0

而不是

LinkedList connections = new LinkedList(); 

使用

LinkedList<PrintWriter> connections = new LinkedList<PrintWriter>(); 

。這確保您只能將PrintWriter放入列表中,並且在將對象從列表中取出時,編譯器會確保取出的對象是PrintWriter,並且不再有問題。