Iterators
ArrayList a = new ArrayList();
a.add("joe");
a.add("pete");
a.add("sue");
a.add("mary");
Iterator i = a.iterator();
while (i.hasNext())
{System.out.println(i.next().; // next returns Object and moves to next element
}
_____________________________________________________________
ArrayList a = new ArrayList();
a.add("joe");
a.add("pete");
a.add("sue");
a.add("mary");
Iterator i = a.iterator();
while (i.hasNext())
{System.out.println(i.next().length()); // won’t work – Objects don’t have lengths
}
__________________________________________________
ArrayList a = new ArrayList();
a.add("joe");
a.add("pete");
a.add("sue");
a.add("mary");
Iterator i = a.iterator(); // declare type of Iterator
while (i.hasNext())
{System.out.println(i.next().length()); // this does work
}
_____________________________________________
ArrayList a = new ArrayList();
a.add("joe");
a.add("pete");
a.add("sue");
a.add("mary");
Iterator i = a.iterator();
while (i.hasNext())
{if (i.next().equals("sue"))
i.remove(); // use of remove in iterator
}
for (String s : a) // new for loop - sue is gone
{System.out.println(s);
}
_____________________________________________________
For LinkedList deleteOdd1 is more efficient because we don't have to traverse
list to find #. For ArrayList - either is equally efficient.
import java.io.*;
import java.util.*;
public class Adder
{private ArrayList list = new ArrayList();
or
private LinkedList list = new LinkedList();
input in = new input();
public void enter()
{for (int x=1; x <= 5; x++)
{list.add((int)(Math.random()*100)); // note we didn't need to convert
}
}
public void deleteOdd1()
{Iterator a = list.iterator();
while (a.hasNext())
{if (a.next() % 2 == 1)
a.remove();
}
}
public void deleteOdd2()
{int x = 0;
while (x < list.size(); x++)
{
if (list.get(x) %2 ==1)
list.remove(x);
else
x++;
}
}
}
|