下面有2段代码,第一次运行代码二正常,但是当第2次运行代码二时,则myList无法通过Iterator来显示其中元素,但是代码二中确实存在,所以实在搞不懂,特来请教下大家~~
代码一:
public class ComUserList { private static File filePath = new File(System.getProperty("user.dir") 
+ File.separator + "userNameList.db");
private static Collection<String> userList = null;
ComUserList(final String userName, Collection<String> myList)throws Exception{
if(filePath.exists()){
try{
myList = getArrayList();
myList.add(userName);
saveArrayList(myList);
}catch(EOFException e){
myList.add(userName);
saveArrayList(myList);
}catch(Exception e){
e.printStackTrace();
}
}else{
try{
filePath.createNewFile();
myList.add(userName);
saveArrayList(myList);
}catch(Exception e){
e.printStackTrace();
}
}
}

@SuppressWarnings("unchecked")
private static Collection<String> getArrayList()throws Exception{
ObjectInputStream readDB = new ObjectInputStream(
new BufferedInputStream(new FileInputStream(filePath)));
userList = (Collection<String>)readDB.readObject();
readDB.close();
return userList;
}

private static void saveArrayList(Collection<String> list)throws Exception{
ObjectOutputStream writeDB = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(filePath)));
writeDB.writeObject(list);
writeDB.close();
}
}代码二:
public class Test4 {
public static void main(String[] args)throws Exception{
//注释下面代码,可运行检测代码段
Collection<String> myList = new LinkedHashSet<String>();
String name = "111";
ComUserList cul = new ComUserList(name, myList);
Iterator<String> it = myList.iterator();
while(it.hasNext()){
System.out.println("yes2");
System.out.println(it.next());
}

//这是检测用的代码
// File filePath = new File(System.getProperty("user.dir") 
// + File.separator + "userNameList.db");
// ObjectInputStream readDB = new ObjectInputStream(
// new BufferedInputStream(new FileInputStream(filePath)));
// Collection<String> userList = (Collection<String>)readDB.readObject();
// Iterator<String> it = userList.iterator();
// while(it.hasNext()){
// System.out.println(it.next());
// }
}
}

解决方案 »

  1.   

    第二次运行时
    后面的
    readDB.close();
    writeDB.close();
    都关闭嘛
      

  2.   

    这我就不明白了,我第二次运行不是都重建了read 和 write了嘛~~
      

  3.   

    if(filePath.exists()){
                try{
                    myList = getArrayList();
                    myList.add(userName);
                    saveArrayList(myList);
                }catch(EOFException e){
                    myList.add(userName);
                    saveArrayList(myList);
                }catch(Exception e){
                    e.printStackTrace();
                }问题出在红色的部分,myList是参数,你调用一个方法,把参数改变了,后面的操作,就是对新的ArrayList操作了,不是对原来的ArrayList操作了.把红色的注掉你再运行一下程序.
      

  4.   

    搞定了,我把构造器里的东西放到一个方法里,然后返回myList,不过不知道为什么1楼的方法注释掉也可以,想不通~~