Java中封装Video类型LinkedList遍历方法无法保留迭代位置如何解决
问题根因
- 每个
ListIterator实例会独立维护遍历进度,你现有playNextVid方法每次调用都会通过video.listIterator()生成全新的迭代器,默认指向列表起始位置,自然无法保留上一次的遍历位置,所以每次调用都只会返回第一个元素。 - case1逻辑正常是因为复用了同一个外部迭代器实例,遍历进度会持续累加。
- 额外注意:你现有
playTheList方法里仅在循环外读取了一次用户输入,循环内不会更新choice变量,会触发死循环,需要把输入读取逻辑移到while循环内部。
修复方案
方案1:复用同一个迭代器实例(推荐)
在playTheList中初始化迭代器,调用playNextVid时将迭代器作为参数传入:
修改后的playTheList代码
public static void playTheList (LinkedList<Video> videoList) { Scanner sc = new Scanner(System.in); boolean out = false; // 全局复用同一个迭代器 ListIterator<Video> iterator = videoList.listIterator(); while (!out) { System.out.println("Choice: "); int choice= sc.nextInt(); // 移到循环内,每次读取用户新选择 switch(choice){ case 1: if(iterator.hasNext()){ Video firstVideo=iterator.next(); System.out.println("****"); System.out.println(" Playing video Name :"+firstVideo.getVideoName()+" Video length: "+firstVideo.getVideoLength()); }else{ System.out.println("End of List"); } break; case 2: // 把迭代器传给playNextVid playNextVid(iterator); break; case 3: out=true; break; } } sc.close(); }
修改后的playNextVid代码
public static void playNextVid(ListIterator<Video> iterator){ if(iterator.hasNext()){ Video currentVideo=iterator.next(); System.out.println("****"); System.out.println(" Playing video Name :"+currentVideo.getVideoName()+" Video length: "+currentVideo.getVideoLength()); }else{ System.out.println("End of List"); } }
方案2:用全局索引记录播放位置
如果需要支持重置播放顺序等额外操作,可以维护索引变量实现:
// 类全局变量记录当前播放位置 private static int playIndex = 0; public static void playNextVid(LinkedList<Video> videoList){ if(playIndex < videoList.size()){ Video currentVideo = videoList.get(playIndex); System.out.println("****"); System.out.println(" Playing video Name :"+currentVideo.getVideoName()+" Video length: "+currentVideo.getVideoLength()); playIndex++; }else{ System.out.println("End of List"); } }
注意:该方案适合数据量小的列表,LinkedList随机查询get操作时间复杂度为O(n),列表过长会影响性能。
内容的提问来源于stack exchange,提问作者user13561105
相关产品推荐
相关产品推荐

