Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding Duplicate Algorithm - Java

I have set of values, an arraylist, and i have to find duplicate keys. One approach is to use 2 loops. and iterate through the list for each value resutling O(n2).

the other thing, That i can do is to put the values as keys in HashTable. I believed, that hashtable would throw an exception if there is already same key in it. But it is not throwing an exception

    Hashtable<String, String> ht = new Hashtable<String, String>();

    for (int i = 0; i<20; i++){
        ht.put(String.valueOf(i%10), String.valueOf(i%10));
    }

do i understand it wrong? Doesn't hastable/hashmap throw exception if there is already same key in it?

like image 703
x.509 Avatar asked May 03 '26 16:05

x.509


2 Answers

My suggestion is you want a HashSet instead of a Hashtable:

Set<String> ht = new HashSet<String>();

for (int i = 0; i<20; i++){
    if ( !ht.add(String.valueOf(i%10)) ) {
       //it already existed, throw an exception or whatever
    }
}

If you don't care about the values that you add to a map, you almost certainly want a Set and not a Map/table.

like image 90
Mark Peters Avatar answered May 05 '26 04:05

Mark Peters


No, it doesn't throw an exception, it simply replaces the old value. You can check if a value already exists by calling get:

if (ht.get(key) != null) {
  // value already exists
}

Edit: As @Mark Peters suggested, containsKey is a simpler and sometimes better solution.

like image 43
casablanca Avatar answered May 05 '26 05:05

casablanca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!