I'm having trouble figuring out how an iterator can be used to replace an element and count the number of elements that were replaced. This is the code I have so far:
public class example {
public static void main (String args[]){
//create an ArrayList
ArrayList<String> list = new ArrayList<String>();
//add elements to the array list
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("B");
list.add("B");
//use iterator to display original list
Iterator iter = list.iterator();
while (iter.hasNext()){
Object element = iter.next();
System.out.println (element + " ");
}
// call replace
String b = "B";
String x = "X";
ArrayList<String> myList = new ArrayList<String>();
replace (b, x, myList);
}
public static <E> int replace(E match, E replacement, ArrayList<E> myList) {
//throw exceptions if null
if (match == null){
throw new IllegalArgumentException ("match cannot be null");
}
if (replacement == null){
throw new IllegalArgumentException ("replacement cannot be null");
}
if (myList == null){
throw new IllegalArgumentException ("myList cannot be null");
}
//return 0 if myList is empty
boolean emptylist = myList.isEmpty();
if (emptylist = true){
System.out.println("0");
}
}
I've used the iterator to print out the elements in the list, but now I have to use the iterator to replace and return the number of replacements. In this case, I want to replace the "B"'s with "X"'s and count the number of "X"'s. I'm assuming I want to put the iterator in the generic method, but I don't really know what direction to head in...
Try using the
ListIterator
class, documented here: http://docs.oracle.com/javase/6/docs/api/java/util/ListIterator.htmlThe documentation for the
set
method describes how to modify list elements.