セットや.contains()メソッドを使用せずに、リストから重複するアイテムを削除することになっているJavaのイントロコースの割り当ての質問に取り組んでいます。基本的には、イテレータと.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;
誰かが私が間違っていることと、代わりにそれをどのように行うべきかを説明してくれるなら、それは非常に役に立ちます。これはテストの準備のためであるため、正しいコードではなく説明をいただければ幸いです。