[英]HashMap method/ parameter
See the following class definition using a HashMap. 请参阅下面的使用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);
}
}
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. 不必将参数复制到局部变量,因为这样一来,您将只有两个变量( name
和_name
)的两个副本。
Moreover, you would probably need to change the line to 此外,您可能需要将行更改为
String name = _name;
to make it compile. 使其编译。
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. 仅在使用getter和setter的情况下才有必要,在这种情况下,您可以使用setter设置局部变量,并使用getter获取更新值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.