The question can be pretty vague, I know. But the reason I ask about this is because the class should have been made with some thought in mind.
This question came to my mind while looking at a few questions here on SO.
Consider the following code:
class A { private int myVar; A(int varAsArg) { myVar = varAsArg; } public static void main(String args[]) { List<A> myList = new LinkedList<A>(); myList.add(new A(1)); myList.add(new A(2)); myList.add(new A(3));
So, as you can see from the above code, I have a replacement for iterating using a for
loop, while I could do the same with the Iterator
method class' hasNext()
and next()
. Similarly, there might be an example of the remove()
method. And experienced users commented on other answers to use the Iterator
class instead of using the for
loop to iterate through the List
. Why?
What else bothers me is that the Iterator
class has only three methods. And the functionality of these functions can be achieved by writing slightly different code.
Some people may argue that the functionality of many classes can be achieved by writing their own code instead of using the class
created for this purpose. Yes, that's right. But, as I said, the Iterator
class has only three methods. So, why you may encounter the problem of creating an additional class when the same task can be performed using a simple block of code that is not too complicated to understand.
EDIT:
While I am in this, as many answers say that I cannot execute the delete function without using Iterator
, I just wanted to know if the following is not consistent: or it will have an undesirable result.
for(A obj : myList) { if(obj.myVar == 1) myList.remove(obj); }
Doesn't this piece of code do the same as remove()
?
source share