hashmapexample.java

来自「java 完全探索的随书源码」· Java 代码 · 共 54 行

JAVA
54
字号
import java.util.HashMap;public class HashMapExample {  public void doExample() {    HashMap myMap = new HashMap(2);    Employee emp = new Employee( "123-45-6789", "Smith", "John" );    myMap.put( emp.getSocialSecurityNumber(), emp );    emp = new Employee( "987-65-4321", "Doe", "Jane" );    myMap.put( emp.getSocialSecurityNumber(), emp );    if ( myMap.containsKey("123-45-6789") ) {      System.out.println("Found by key: " + myMap.get("123-45-6789"));    }    if ( myMap.containsValue(emp) ) {      System.out.println("Map contains value: " +        myMap.get(emp.getSocialSecurityNumber()));    }    // clear the list and verify that it's empty    myMap.clear();    System.out.println("Map is now " +      (myMap.isEmpty() ? "Empty" : "Not Empty"));  }  public static void main( String args[] ) {    new HashMapExample().doExample();  }}class Employee {  private String socialSecurityNumber;  private String lastName;  private String firstName;  public Employee( String ssn, String lname, String fname ) {    socialSecurityNumber = ssn;    lastName = lname;    firstName = fname;  }  // the SSN can be retrieved, but is immutable, which  // is best for an object used as a key  public String getSocialSecurityNumber() {    return socialSecurityNumber;  }  public String toString() {    return socialSecurityNumber + " " + lastName + ", " + firstName;  }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?