Kareem
Kareem

Reputation: 889

String operation in recursive function causing stackoverflow

I am building recursive function that go through a million line or so, I get stackOverFlow from this function during execution.

protected String[] getConnectedCities(String line) {
    return line.trim().toLowerCase().replace(DELIMITER + " ", DELIMITER)
            .split(DELIMITER);
}

This is the full code:

    protected final Map<String, City> processLine(
        final Map<String, City> dataMap) {
    try {
        String line = "";
        if ((line = bReader.readLine()) == null) {
            return dataMap;
        }
        // Check if direct relation can be found
        String connectedCities[] = parseLine(line);
        line = null;
        saveConnection(dataMap, connectedCities);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return processLine(dataMap);
}

I am not sure what am I doing wrong, I think it is related to the String line but am not quite sure what is it.

Thanks.

Upvotes: 0

Views: 83

Answers (1)

user3458
user3458

Reputation:

The last thing you do, you're calling processLine agan. This will have as many levels of recusion as you have lines in file, until return statement above bails out. This is technically tail recursion, but Java may not understand that.

Upvotes: 1

Related Questions