codingmachine
codingmachine

Reputation: 23

Returning Collections

I am trying to return a collection containing connections in a network that starts or ends at a specific station. I am having trouble figuring out how to return it and take the station parameter. Also is having the creation of the hashMap in the method the right way to do it, or should it be created outside of it?

It is giving me the error incompatible types: Connection cannot be converted to Collection<Connection> for the return statement

CODE:

/**
 * Return a Collection containing all the Connections in the network that
 * start or end at a specified station
 *
 * @param station Station to/from which the Connection should run
 *
 * @return a Collection containing all the connections that start or end at
 * the specified station
 */

@Override
public Collection<Connection> getConnectionsFrom(Station station) {
    Map<Station, Connection> stationConnectionFrom = new HashMap<Station, Connection>();
    return stationConnectionFrom.get(station);
}

Upvotes: 1

Views: 82

Answers (2)

Yevhen Surovskyi
Yevhen Surovskyi

Reputation: 961

If you can't change method signature, you can do:

@Override
public Collection<Connection> getConnectionsFrom(Station station) {
    Map<Station, Connection> stationConnectionFrom = new HashMap<Station, Connection>();
    return Collections.singletonList((stationConnectionFrom.get(station));
}

Upvotes: 1

Jean Logeart
Jean Logeart

Reputation: 53809

Only one Connection is being returned. You can change your return type to:

public Connection getConnectionFrom(Station station) {
    Map<Station, Connection> stationConnectionFrom = new HashMap<>();
    return stationConnectionFrom.get(station);
}

In your case, the map being empty, this will always return null.

Upvotes: 2

Related Questions