我无法弄清楚如何使用迭代器替换元素并计算被替换元素的数量。这是我到目前为止的代码:
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");
}
}
我已经使用迭代器打印出列表中的元素,但现在我必须使用迭代器来替换并返回替换的数量。在这种情况下,我想用“X”替换“B”并计算“X”的数量。我假设我想将迭代器放在泛型方法中,但我真的不知道该往哪个方向前进......