我目前正在編寫一個小小的網絡事物,並希望cicle拋出所有我的玩家,所以我使用ArrayLists和列表,但有很多Exception,因此深入到問題我用迭代器替換了它們,但是我在所有「it.next()」中都得到併發修改異常:/。 所以,如果請你可以幫助我瞭解問題:)。iterator.next()中的ConcurrentModificationException我找不到另一個解決方案
@Override
public void run()
{
StringBuilder l = new StringBuilder();
Iterator<UUID> pc;
Iterator<Packet> pa;
while (Jelly.isSTATUS()) {
pc = Jelly.getOnlinePlayers().keySet().iterator();
while (pc.hasNext())
try {
System.out.println("ENTERED!");
Player p = Jelly.getOnlinePlayers().get(pc.next());
System.out.println(p.getIGN());
if (Packetsts.containsKey(p) && !Packetsts.get(p).isEmpty())
try {
pa = Packetsts.get(p).iterator();
while(pa.hasNext()) {
Packet i = pa.next();
for (String j : i.getData())
l.append(j + ",");
l.append("es");
System.out.println("Data: " + l.toString());
byte[] toSendBytes = l.toString().getBytes();
int toSendLen = toSendBytes.length;
byte[] toSendLenBytes = new byte[4];
toSendLenBytes[0] = (byte)(toSendLen & 0xff);
toSendLenBytes[1] = (byte)(toSendLen >> 8 & 0xff);
toSendLenBytes[2] = (byte)(toSendLen >> 16 & 0xff);
toSendLenBytes[3] = (byte)(toSendLen >> 24 & 0xff);
PrintStreams.get(p).write(toSendLenBytes);
PrintStreams.get(p).write(toSendBytes);
Packetsts.get(p).remove(i);
l.setLength(0);
}
} catch (Exception ex) { }
} catch (ConcurrentModificationException ex){ ex.printStackTrace(); }
}
System.out.println("END!");
}
謝謝:)
UPDATE:
@Override
public void run()
{
StringBuilder l = new StringBuilder();
Iterator<UUID> pc = Jelly.getOnlinePlayers().keySet().iterator();
Iterator<Packet> pa;
while (Jelly.isSTATUS())
if (!Jelly.getOnlinePlayers().keySet().isEmpty()) {
pc = Jelly.getOnlinePlayers().keySet().iterator();
while (pc.hasNext()) {
UUID u = pc.next();
Player p = Jelly.getOnlinePlayers().get(u);
if (Packetsts.containsKey(p) && !Packetsts.get(p).isEmpty())
try {
pa = Packetsts.get(p).iterator();
while(pa.hasNext()) {
Packet i = pa.next();
for (String j : i.getData())
l.append(j + ",");
l.append("es");
System.out.println("Data: " + l.toString());
byte[] toSendBytes = l.toString().getBytes();
int toSendLen = toSendBytes.length;
byte[] toSendLenBytes = new byte[4];
toSendLenBytes[0] = (byte)(toSendLen & 0xff);
toSendLenBytes[1] = (byte)(toSendLen >> 8 & 0xff);
toSendLenBytes[2] = (byte)(toSendLen >> 16 & 0xff);
toSendLenBytes[3] = (byte)(toSendLen >> 24 & 0xff);
PrintStreams.get(p).write(toSendLenBytes);
PrintStreams.get(p).write(toSendBytes);
l = new StringBuilder();
}
Packetsts.get(p).clear();
} catch (Exception ex) { ex.printStackTrace(); }
}
}
System.out.println("END!");
}
線 「UUID U = pc.next();」請,我真的很討厭併發修改例外:/
如果您想在遍歷該集合的同時修改集合,則必須通過調用其中一個迭代器的方法來完成修改。那麼Packetsts.get(p).remove(i)有什麼問題。刪除必須通過調用iterator.remove()來完成。 –
你最終的目標是什麼?刪除所有包後? – AbtPst
此外,請停止捕獲ConcurrentModiciationException和Exception。這些例外不應被捕獲。特別是如果你忽略它們。 –