Java ArrayList remove dupes without sets

Posted by Kieran on Stack Overflow See other posts from Stack Overflow or by Kieran
Published on 2012-12-02T16:47:07Z Indexed on 2012/12/02 17:04 UTC
Read the original article Hit count: 229

Filed under:
|

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.

© Stack Overflow or respective owner

Related posts about java

Related posts about arraylist