Monday, November 25, 2013

My Logic is messed up. I am just trying to work out a pay to remove duplicates in an arrayList without using a HashSet.
public static void main(String[] args) {

    ArrayList<String> wordDulicate = new ArrayList<String>();

    wordDulicate.add("Tom");
    wordDulicate.add("Jones");
    wordDulicate.add("Sam");
    wordDulicate.add("Jamie");
    wordDulicate.add("Robie");
    wordDulicate.add("Helen");
    wordDulicate.add("Tom");
    wordDulicate.add("Troy");
    wordDulicate.add("Mika");
    wordDulicate.add("Tom");



    for (String dupWord : wordDulicate) {
        if(wordDulicate.equals(dupWord))
            System.out.println(wordDulicate.get(dupWord));
    }
}
}
share|improve this question
 
Then you can create a new list and add items to it.. skipping duplicates.. –  Rohit Jain Oct 2 '12 at 19:48
2 
Just out of curiosity or is use of HashSet prohibited by the teacher? :) –  halex Oct 2 '12 at 19:48
 
how is for (int dupWord : wordDulicate) { compiling? –  gtgaxiola Oct 2 '12 at 19:48
 
Does this even compile? –  Tudor Oct 2 '12 at 19:49
 
dupWord should be a String not an int –  doublesharp Oct 2 '12 at 19:49 
show 2 more comments

4 Answers

This methodology requires having another list:
       ArrayList<String> wordDulicate = new ArrayList<String>();

        wordDulicate.add("Tom");
        wordDulicate.add("Jones");
        wordDulicate.add("Sam");
        wordDulicate.add("Jamie");
        wordDulicate.add("Robie");
        wordDulicate.add("Helen");
        wordDulicate.add("Tom");
        wordDulicate.add("Troy");
        wordDulicate.add("Mika");
        wordDulicate.add("Tom");

        ArrayList<String> nonDupList = new ArrayList<String>();

        Iterator<String> dupIter = wordDulicate.iterator();
        while(dupIter.hasNext())
        {
        String dupWord = dupIter.next();
        if(nonDupList.contains(dupWord))
        {
            dupIter.remove();
        }else
        {
            nonDupList.add(dupWord);
        }
        }
      System.out.println(nonDupList);
Output:
[Tom, Jones, Sam, Jamie, Robie, Helen, Troy, Mika]
share|improve this answer
3 
Why are you removing from original list? –  maba Oct 2 '12 at 19:55
 
I thought that was requirement, if NOT, we can do just ! (NOT) check. –  Nambari Oct 2 '12 at 19:56 
 
I'm new to Iterator. Can I ask why you used to Iterator? –  AppSensei Oct 2 '12 at 20:01
 
Iterator allows you to loop through the collection. docs.oracle.com/javase/1.5.0/docs/api/java/util/Iterator.html–  Nambari Oct 2 '12 at 20:03
 
So, is that the best way to loop through a collection? –  AppSensei Oct 2 '12 at 20:05
show 3 more comments

No comments: