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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With