Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 442
Ani Avatar asked Jul 26 '26 00:07

Ani


2 Answers

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.

like image 119
Shree Krishna Avatar answered Jul 27 '26 13:07

Shree Krishna


If the definition of LetterCounter class is as follows:

public class LetterCounter extends ArrayList<String>{
        // implementation

}

You do not need to cast at all. This is because Java allows covariant return type. Please look at What is a covariant return type?

like image 33
Sanjeev Saha Avatar answered Jul 27 '26 13:07

Sanjeev Saha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!