0

https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/

This code is to generate all possible strings, when each digit between 2 to 9 (inclusive) are mapped to English alphabet string.

The question is to recreate mobile phone T9 dictionary, which means, if user types 23, then all possible combinations of strings of "abc" and "def" should be returned.

enter image description here

https://ideone.com/4FodC8

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(letterCombinations("23"));
    }

    private static final String[] KEYS = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };

        public static List<String> letterCombinations(String digits) {
            List<String> ret = new LinkedList<String>();  //this is the local variable.
            combination("", digits, 0, ret);  //being sent to a method. But that method doesn't have any return type.
            return ret; //so, how is this ret being populated????
        }

        private static void combination(String prefix, String digits, int offset, List<String> ret) {
            if (offset >= digits.length()) {
                ret.add(prefix);
                return;
            }
            String letters = KEYS[(digits.charAt(offset) - '0')];
            for (int i = 0; i < letters.length(); i++) {
                combination(prefix + letters.charAt(i), digits, offset + 1, ret);
            }
        }
}

How does the ret declared and instantiated within letterCombination() method gets set, when combination( ) method doesn't have a return type.

sofs1
  • 3,834
  • 11
  • 51
  • 89

2 Answers2

5

Java is 100% pass by value, however, objects which might appear to values are actually always references to objects. These references are passed by value. https://stackoverflow.com/a/40523/57695

In languages like C or C++ a reference has a special syntax, however in Java, variables are only references or primitives so there is no reason to have a special syntax.

The new LinkedList<String>() isn't a local variable on the stack. It's an object on the heap. It is not copied when you pass a reference to it, nor is it made read-only in some way. If you modify it in another method or in another thread, it gets changed.

Your ret local variable is just a reference to that heap object. You can't change that reference in another method, but you can change the object referenced. This is because the reference is copied, but only the reference is copied.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

because in the method invocation here

combination("", digits, 0, ret); // 

the argument ret here has also a reference to ret object below

List<String> ret = new LinkedList<String>();
The Scientific Method
  • 2,374
  • 2
  • 14
  • 25