views:

111

answers:

3
+1  Q: 

Covariance in Java

Why does the following not work in Java? It would work in C#:

public static final List<String> Split(String str, char delimiter)
    {
        if ((str == null) || "".equals(str))
        {
            return new CopyOnWriteArrayList<String>();
        }
    }

I get an error saying this method has to return List. CopyOnWriteArrayList implements the List interface. Why does covariance not apply on return values in Java?

+8  A: 

It looks like you've forgotten to return a List<String> for the else branch.

Stephen
right!!...compiler error....ha ah..those red lines in eclipse are damn too revealing
Suraj Chandran
ahh! that's right. I thought it was telling me I couldn't return CopyOnWriteArrayList<String> as a List<String>.
Bobby
I'm upset, I'm not as much of an eagle eye as I used to be. I should have seen that right off the bat... I need to stop being so reliant on my IDE.
Meiscooldude
A: 

You either have a else branch explicitly and return whatever you want to return (null maybe ?). Or have a return statement at the end of the method. You program will not compile if you do not have either.

Bragboy
A: 

Apart from the correct answers above:

  1. use lower case method names in Java (split instead of Split)
  2. why return such a heavy object as CopyOnWriteArrayList when your string is empty? That's the kind of situation where you want to return Collections.emptyList(), where no new object is created unnecessarily (assuming you are not going to add values to the list afterwards)

Actually, I'd use apache commons lang and do it like this:

return Arrays.asList(
    StringUtils.stripToEmpty(myString) // converts null into ""
                                 // and strips extra whitespace
        .split(
             Pattern.quote(Character.toString(delimiter))
        )
)

No if / else needed.

seanizer