Java ArrayList remove dupes without sets
- by Kieran
I'm having problems removing duplicates from an ArrayList. It's for an assignment for college. Here's the code I have already:
public int numberOfDiffWords() {
ArrayList<String> list = new ArrayList<>();
for(int i=0; i<words.size()-1; i++) {
for(int j=i+1; j<words.size(); j++) {
if(words.get(i).equals(words.get(j))) {
// do nothing
}
else {
list.add(words.get(i));
}
}
}
return list.size();
}
The problem is in the numberOfDiffWords() method. The populate list method is working correctly, as my instructor has given me a sample string (containing 4465 words) to analyse - printing words.size() gives the correct result.
I want to return the size of the new ArrayList with all duplicates removed.
words is an ArrayList class attribute.
UPDATE: I should have mentioned I'm only allowed to use dynamic indexed-based storage for this part of the assignment, which means no hash-based storage.