1

Here's my code:

public static void deleteDuplicates(ArrayList<String> list){
    ArrayList<String> newList = new ArrayList<String>();
    HashSet<String> set = new HashSet<String>();

    for(int i = 0; i < list.size(); i++){
        set.add(list.get(i));
    }

    newList.addAll(set);
    return newList;
}

My input for this is the following:

1, 2, 2, 3, 4, 3, 1, 5, 5, 4, 1, 4, 5

And the output I'm getting is:

3, 2, 4, 1, 5

Can anyone explain why this is out of order?

Matthew Brzezinski
  • 1,685
  • 4
  • 29
  • 53

3 Answers3

5

Change HashSet for LinkedHashSet:

Hash table and linked list implementation of the Set interface, with predictable iteration order.

Also, remember to always program to an interface:

public static void deleteDuplicates(List<String> list){
    List<String> newList = new ArrayList<String>();
    Set<String> set = new LinkedHashSet<String>();
    //rest of your code
}
Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • 1
    @user1327636 don't forget to program interface oriented, not to class implementations (check the link provided in my answer). – Luiggi Mendoza Feb 19 '13 at 03:19
1

Quoting from the HashSet class documentation:

It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.

christianhs
  • 81
  • 1
  • 4
1

I'm sure there's a more effecient way but here's an idea for an n^2 algorithm for removal

public static void deleteDuplicates(ArrayList<String> list){
ArrayList<String> newList = new ArrayList<String>();

for (int i = 0; i < list.size(); i++){

boolean exists = false;
String str = list.get(i);
for (int j = 0; j < newList.size(); j++){
if (newList.get(j).compareTo(str)==0){
exists = true;
break;
}
}
if (!exists) newList.add(str);
}
return newList;
}
Alex
  • 1,388
  • 1
  • 10
  • 19