你能解释一下收藏中的概念吗 [英] Can you explain me the concept in collection

查看:147
本文介绍了你能解释一下收藏中的概念吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Arraylist列表= new Arraylist();
迭代器itr = list.iterator();
While(itr.hasNext)

为什么还要创建另一个对象"itr",因为iterator接口也是在Arraylist类中实现的?
为什么我们不能编程呢?
Arraylist列表= nee Arraylist();
While(list.hasnext)

我尝试过的事情:

您能不能用example

Arraylist list = new Arraylist();
Iterator itr =list.iterator();
While(itr.hasNext)

Why do we create an another object "itr" since iterator interface is implemented in Arraylist class also ?
Why cant we program it has?
Arraylist list = nee Arraylist();
While(list.hasnext)

What I have tried:

Can you please explain with example

推荐答案

解释一下.您正在做的是创建一个名为itr的变量,该变量在集合上保留一个迭代器-您可以通过向集合询问一个新对象(从集合中的第一个对象开始指向")来获取此实例. />
假设您是对的,并且每个集合只有一个迭代器?如果两个线程需要访问同一集合,将会发生什么?或什至是两种方法,两种方法都因不同的原因而访问了同一集合,而又碰巧其中一种方法间接调用了另一种方法?还是即使您嵌套"了while循环?
You don''t. What you are doing is creating a variable called itr which holds an iterator over the collection - you get an instance of this by asking the collection for a new object which starts off "pointed" at the first object in the collection.

Suppose you were right, and there was only one iterator per collection? What would happen if two threads needed to access the same collection? Or even two methods, both of which accessed the same collection for different reasons, and which happened to have one of them indirectly call the other? Or even if you "nested" while loops?
Arraylist list = new Arraylist();
While(list.hasnext) {
   ...
   While(list.hasnext) {
      ...
   }
...
}


仅使用一个迭代器,两个迭代器的外循环"就会被内循环"严重弄乱.那将是不好的,因为您不应该知道"一种方法的工作原理,您可以调用它并完成它的工作.但是,如果只有一个迭代器,那么如果一个方法使用它,那么您将需要知道,因为您无法在自己的循环中调用该方法而不会出现问题.

在需要时获取新的迭代器意味着不会发生此类问题-因为您在集合上而不是集合本身上迭代迭代器!


With only one iterator, the "outer loop" of the two would get seriously messed up by the "inner loop". That would be bad, because you aren''t supposed to "know" how a method works - you call it and it does it''s job. But if there is only one iterator, if a method uses it, you would need to know because you can''t call that method inside your own loop without problems.

Fetching a new iterator when you need one means that such problems just don''t happen - because you iterate the iterator over the collection, not the collection itself!


这篇关于你能解释一下收藏中的概念吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆