Ani Ani - 6 months ago 13
Java Question

Casting List<String> to a String return type

The method (below) is a

List<String>
type and the class that I'm using as a parameter is a
String
. I was wondering if the way I'm casting would work:

return (List<String>) subList;


This is the method:

public List<String> getWords(String phrase) {
LetterCounter subList = new LetterCounter(phrase);
if (phrase == null) throw new IllegalArgumentException();
for (String element : dict) {
if (subList.contains(element))
subList.add(element);
}
return (List<String>) subList;
}// End of getWords


This URL points to the
LetterCounter
class:

http://pastebin.com/XbeUSvPx

I put it in paste bin because the class is too long.

Answer

Better creating new instance of List<String> and adding String element to that like,

public List<String> getWords(String phrase) {
    LetterCounter subList = new LetterCounter(phrase);
    if (phrase == null) throw new IllegalArgumentException();
     List<String> str = new List<>();
    for (String element : dict) {
        if (subList.contains(element))
            str.add(element);
    }
    return str;
}

I'm suggesting this, because Your element in loop is String.

Comments