Reputation: 11
See the following class definition using a HashMap.
Why is it not necessary to pass formal parameters of the methods to local parameters as I did in the second method?
import java.util.HashMap;
public class MapTester
{
private HashMap<String, String> phoneBook = new HashMap<String, String> ();
public MapTester()
{
phoneBook.put("Homer Jay Simpson", "(531) 9392 4587");
phoneBook.put("Charles Montgomery Burns", "(531) 5432 1945");
phoneBook.put("Apu Nahasapeemapetilon", "(531) 4234 4418");
}
public void enterNumber(String name, String number)
{
phoneBook.put(name, number);
}
public String lookupNumber(String _name)
{
name = _name;
return phoneBook.get(name);
}
}
Upvotes: 0
Views: 2492
Reputation: 7836
You can directly use formal parameters without copying it into local parameter because it will get original value, when function is called.
public String lookupNumber(String _name)
{
return phoneBook.get(_name);
}
It is necessary only in the case of getter and setter, where you set the local variable using setter and get updated value using getter.
Upvotes: 0
Reputation: 6640
It is not necessary to copy the parameter to a local variable, because then you would have two copies of the same variable (name
and _name
) while you need only one.
Moreover, you would probably need to change the line to
String name = _name;
to make it compile.
Upvotes: 1