我正在尝试为我的 Java 入门课程处理作业问题,我们应该在不使用集合或 .contains() 方法的情况下从列表中删除重复项。基本上只使用迭代器和 .equals() 方法。我的代码如下:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class sample {
public static void main(String[] args) throws BadListException {
List<String> myList = new ArrayList<String>();
myList.add("A");
myList.add("B");
myList.add("B");
myList.add("C");
myList.add("B");
myList.add("D");
unique(myList);
System.out.println(myList);
}
public static List<String> unique( List<String> items ) throws BadListException {
List<String> newList = new ArrayList<String>();
Iterator<String> itr = items.listIterator();
// If items is null, throw a BadListException.
if (items == null){
throw new BadListException();
}
// If items is empty, return a new empty list.
if (items.isEmpty()){
return newList;
}
// Otherwise create and return a new list that contains the items
// in L with all duplicates removed.
// Example: items: "A","B","C" result: "A","B","C"
// Example: items: "A","A","A" result: "A"
// Example: items: "A","B","B","C","A","D" result: "A","B","C","D"
while (itr.hasNext()){
for (int i = 0; i < items.size()-1; i++){
if (itr.next().equals(items.get(i))){
itr.remove();
}
}
}
items = newList;
return newList;
如果有人可以解释我做错了什么以及我应该如何去做,那将非常有帮助。请注意,由于这是为我准备测试,我希望得到解释,而不仅仅是正确的代码。