-2

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?

paul
  • 4,333
  • 16
  • 71
  • 144

2 Answers2

2

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

Two things,

First, Arrays.asList(strMOd) returns you ArrayList which is inner class defined in Array.java and it cannot be casted to LinkedHashSet as both are different types.

Second, for your example you dont need to do any casting or conversions. ArrayList returned by Arrays.asList implements List<>, and Collections.frequency accepts anything which implements Collection and as List extends that interface you could do that.

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

        }
user902383
  • 8,420
  • 8
  • 43
  • 63