[英]Serializing a List<List<String>> infinite loop iterator.hasNext() JAVA
I've been trying to serialize a List<List< String >>
in Java but my code gets stucks in a loop.我一直在尝试序列化 Java 中的List<List< String >>
但我的代码陷入了循环。 Here's the code:这是代码:
public void Serializing(List<List<String>> player,File file ) throws IOException{
try {
fileOut=new FileOutputStream(file);
out= new ObjectOutputStream(fileOut);
Iterator <List <String>> it=player.listIterator();
while(it.hasNext()){ //Somehow if i don't put this just adds my first element
out.writeObject(player.listIterator().next());
}
fileOut.close();
out.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(ManejoInformacion.class.getName()).log(Level.SEVERE, null, ex);
}
}
I'm adding the deserializable method just in case我正在添加可反序列化的方法以防万一
public List<List<String>> deserializable(File file) throws FileNotFoundException, IOException, ClassNotFoundException{
ObjectInputStream in;
List<List<String>> info;
try (FileInputStream fileIn = new FileInputStream(file)) {
in =new ObjectInputStream(fileIn);
info = new ArrayList<>();
info =(List<List<String>>)in.readObject();
} in.close();
return info;
}
Hope this is enough: Thank you :)希望这就足够了:谢谢:)
Here:这里:
out.writeObject(player.listIterator().next());
you're creating a new iterator.您正在创建一个新的迭代器。 But you already had an iterator, and you need to use that one so its state is updated.但是你已经有了一个迭代器,你需要使用那个迭代器来更新它的 state。
out.writeObject(it.next());
Otherwise it.hasNext()
stays true because you're not taking items from it
.否则it.hasNext()
保持真实,因为您没有it
获取项目。
Alternatively, get rid of all reference to iterators, get rid of the while-loop, and just use a for-loop:或者,摆脱对迭代器的所有引用,摆脱 while 循环,只使用 for 循环:
for (List<String> item: player) {
out.writeObject(item);
}
The for-loop handles the iterator implicitly, so you don't have to. for 循环隐式处理迭代器,因此您不必这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.