简体   繁体   中英

HashMap method/ parameter

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);
    }   
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM