0

I have the below method which checks if given two strings have atleast one character in common

String checkCommonCharacters(String s1, String s2) {
    Set<String> s1Chars = new HashSet(Arrays.asList(s1.split("")));
    Set<String> s2Chars = new HashSet(Arrays.asList(s2.split("")));

    String res = Collections.disjoint(s1Chars, s2Chars) ? "NO" : "YES";
    System.out.println(res);
    return res;
}

Above code works fine but if I change it to a Character set it doesnt work. Having the hashcode() and equals() in Character class why HashSet is not behaving the same way as of String type?

Set<Character> s1Chars = new HashSet(Arrays.asList(s1.toCharArray()));
Set<Character> s2Chars = new HashSet(Arrays.asList(s2.toCharArray()));

Example:
Input s1="abc", s2="dea" output is YES for String type
Input s1="abc", s2="dea" output is NO for Character type

OTUser
  • 3,788
  • 19
  • 69
  • 127
  • `toCharArray` doesn't return `Character[]` but `char[]`. See [Jon's answer](https://stackoverflow.com/a/1467940) from duplicate question which explains problem with primitive arrays and generics. – Pshemo Mar 13 '19 at 03:01
  • Could you show us the input for "doesn't work?" I'd like to see exactly what isn't working. – markspace Mar 13 '19 at 03:01
  • @markspace for any given input its not working with `Character` type `Set`, input is updated in question – OTUser Mar 13 '19 at 03:05

0 Answers0