Search code examples
javaarrayslinkedhashset

java.util.Arrays$ArrayList cannot be cast to java.util.LinkedHashSet


I want to write a java program that will give me frequency of letters in a given String.

I have tried this:

public void frequencyOfLetter() {
    String strMOd[] = "Hurricane.".split("");
    LinkedHashSet<String> lhs = (LinkedHashSet<String>) Arrays.asList(strMOd);
for (String letter : lhs) {
        if (lhs.contains(letter)) {
            System.out.println(letter + " " + Collections.frequency(lhs, letter));
        }

    }


}

Why I am using LinkedHashSet because I do not want any duplicates. However this is giving me error that this kinda casting is not correct.

So I used this as few extra line of code:

List<String> lhs = Arrays.asList(strMOd); LinkedHashSet<String> lhsmod = new LinkedHashSet<String>(lhs);

Why previous code was giving that error and what is the better of doing it with help of LinkedHashSet?


Solution

  • The cast will fail because two types are unrelated: LinkedHashSet is neither a supertype nor a subtype of Arrays$ArrayList, so there is no way that a reference to an Arrays$ArrayList can contain something which can be cast to a LinkedHashSet.

    You can very easily create a LinkedHashSet from an array:

    LinkedHashSet<String> lhs = new LinkedHashSet<>(Arrays.asList(strMOd));
    

    The difference between this code and your previous code is that this code creates a new instance of LinkedHashSet, copying in the elements of the list.