user3447234
user3447234

Reputation: 11

LinkedHashSet appears to be leaving a duplicate element

I am curious if anyone knows why the first element in my LinkHashSet seems to be allowing duplicates? I am doing a code challenge from CodeEval and when I input values 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6 the output from my program displays 2, 2, 3, 4, 5, 6 It's only the first element that is causing the problem.

I am using jre 1.8.0_45. I got tired of troubleshooting the issue and checked in the challenge and the website accepted my solution, so I am wondering if there is a bug in my version of Java. I searched and have seen no other posts of anyone having issues with LinkHashSet producing duplicates.

import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;


public class UniqueElements 
{

    public static void main(String[] args) {
        Scanner  s = new Scanner(System.in);
        String line = s.nextLine();

        List<String> list = Arrays.asList(line.trim().split(","));

        Set<String> string = new LinkedHashSet<>(list);

        Iterator<String> iter = string.iterator();

         while (true) 
         {
             System.out.print(iter.next());

             if (iter.hasNext()) {
                 System.out.print(",");
             } else {
                 System.out.println();
                 break;
             }
         }

    }
}

Upvotes: 1

Views: 200

Answers (2)

Erick G. Hagstrom
Erick G. Hagstrom

Reputation: 4945

You've wisely used the trim() method, but you're not getting all the whitespace from between the list entries. Did you notice that your output list has spaces between the numbers, but your output println doesn't insert any?

The first "2" has no leading whitespace. The second " 2" has a leading space. That makes them different Strings. Get rid of the space, get rid of the problem.

Using a different regular expression on your split() would help. How about .split(",\\s*")?

Another option: why are you using String values in the first place? If they are all numeric and guaranteed to be so (and the challenge would state that), then converting to Number (or even Integer, if that's the guarantee) would make the extraneous spaces irrelevant.

Upvotes: 1

assylias
assylias

Reputation: 328598

Your problem is here:

List<String> list = Arrays.asList(line.trim().split(","));

It creates a list where the first element is "2" and the second is " 2" (note the leading space).

You need to remove the spaces from the input or split on ", " or "\\s*,\\s*" to allow for spaces before and after the commas.

Upvotes: 3

Related Questions