只是一個免責聲明:我第二次重複了我的java mod,所以我的問題可能會有點簡單,希望我聽起來不太愚蠢。去除arraylist中的重複項
寫方法removeDuplicates是作爲一個參數排序的 ArrayList的字符串,並從列表中排除任何重複。 例如,假設名爲list的變量包含以下值 :
{"be", "be", "is", "not", "or", "question", "that", "the", "to", "to"}
調用removeDuplicates(list);列表 應存儲以下值:{"be", "is", "not", "or", "question", "that", "the", "to"}
因爲值將被排序,所有重複項將被組合在一起。
我嘗試這個:
public static void removeDuplicates(ArrayList <String>a){
for(int i=0;i<a.size();i++){
String word=a.get(i);
String word2=a.get(i+1);
if(word.equals(word2)){
a.remove(word);
}
else{
System.out.print(word);
}
}
}
的問題是,當我把它叫做:
["duplicate", "duplicate", "duplicate", "duplicate", "duplicate"]
返回indexoutofbound
。我知道這與i=i-1
有關,並參考remove
方法。嘗試插入它在這裏,但它不起作用。但是我很困惑,因爲這與我的代碼一起工作。當我打電話給:
["be", "be", "is", "not", "or", "question", "that", "the", "to", "to"]
它的工作原理。
這是否幫助? http://stackoverflow.com/questions/13429119/get-unique-values-from-arraylist-in-java – Aiias 2013-04-07 05:54:03
爲什麼不能使用一個相同的集合。這不會讓您在第一時間輸入重複值。 – 2013-04-07 05:54:04
你好啊,它並沒有真正的幫助。我不喜歡設置的方法。因爲它沒有被教導,所以會更喜歡與設置無關的東西 – user2179615 2013-04-07 05:56:33