我正在为我的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;
如果有人能够解释一下我做错了什么以及我应该怎样做,那将非常有帮助。请注意,由于这是为了准备测试,所以我希望得到解释而不仅仅是正确的代码。
newList
,而你从未更改它。 - El Hocko