我无法弄清楚迭代器如何用于替换元素并计算被替换的元素数量。这是我到目前为止的代码:
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”的数量。我假设我想把迭代器放在泛型方法中,但我真的不知道要进入哪个方向......
答案 0 :(得分:1)
你遍历列表,当你找到匹配的元素时,你set
替换它:
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");
}
int counter = 0;
ListIterator<E> iter = myList.listIterator();
while (iter.hasNext()) {
E val = iter.next();
if (val.equals(match)) {
iter.set(replacement);
++counter;
}
}
return counter;
}
答案 1 :(得分:0)
尝试使用此处记录的ListIterator
课程:http://docs.oracle.com/javase/6/docs/api/java/util/ListIterator.html
set
方法的文档描述了如何修改列表元素。
答案 2 :(得分:0)
你不需要迭代器来替换元素,当你在它上面循环时添加或删除元素时需要它。你可以用简单的for循环进行替换。
public class example {
public static void main (String[] args) throws java.lang.Exception
{
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");
String b = "B";
String x = "X";
System.out.print(replace (b, x, list));
}
public static <E> int replace(E match, E replacement, ArrayList<E> myList) {
//throw exceptions if null
if (match == null || replacement == null || myList == null ){
throw new IllegalArgumentException ("match cannot be null");
}
int i=0;
int replaceCount=0;
for(E str : myList){
if(str.equals(match)){
myList.set(i,replacement);
replaceCount++;
}
i++;
}
return replaceCount;
}
}