关于Map的讲解实例电话本

电话本的列子

 Map map=new HashMap();

 map.put(key,value)

map.get(key)

package cn.jsj.jcf.p8;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;

public class MapDemo1 {

    private static Map<String, Integer> phonebook=new HashMap<String, Integer>();
	public static void main(String[] args) {
		System.out.println("Reading in phone numbers:");
		readPhonenNmbers();
		System.out.println("Looking up phone numbers");
		lookupNumbers();
		System.out.println("Displaying all numbers");
		displayAllNumbers();
	}
	private static void displayAllNumbers() {
		Iterator<String> iterator=phonebook.keySet().iterator();
		while(iterator.hasNext()){
			String name=iterator.next();
			Integer number=phonebook.get(name);
			System.out.println(name+":"+number);
		}
	}
	private static void lookupNumbers() {
		Scanner input=new Scanner(System.in);
		while(true){
			System.out.println("Enter name:");
			String name=input.next();
			if("end".equals(name))
				break;
			Integer phonenumber=phonebook.get(name);
			if(phonenumber==null){
				System.out.println(name+"is not in the phonebook!");
			}else{
				System.out.println(phonenumber);
			}
		}
	}
	private static void readPhonenNmbers() {
		Scanner input=new Scanner(System.in);
		while(true){
			System.out.println("Enter name:");
			String name=input.next();
			if("end".equals(name))
				break;
			System.out.println("Enter phonenumber:");
			Integer phonenumber=input.nextInt();
			phonebook.put(name,phonenumber);			
		}
	}

}


你可能感兴趣的:(关于Map的讲解实例电话本)