晕倒这个问题,有点搞不明白了

llm0528 2009-07-17 11:30:14
下面有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());
// }
}
}
...全文
109 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
pmlxp 2009-07-17
  • 打赏
  • 举报
回复
第二次运行时
后面的
readDB.close();
writeDB.close();
都关闭嘛
llm0528 2009-07-17
  • 打赏
  • 举报
回复
搞定了,我把构造器里的东西放到一个方法里,然后返回myList,不过不知道为什么1楼的方法注释掉也可以,想不通~~
bigbug9002 2009-07-17
  • 打赏
  • 举报
回复
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操作了.把红色的注掉你再运行一下程序.
llm0528 2009-07-17
  • 打赏
  • 举报
回复
这我就不明白了,我第二次运行不是都重建了read 和 write了嘛~~

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧