HashMap Demo

3205 ワード

package com.gaoyuan.HashMap;

public class Info {

	private String phone;

	private String email;

	public Info(String phone,String email){
		this.phone = phone;
		this.email = email;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
}

 
package com.gaoyuan.HashMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class PhoneBook {

	private static Map phoneMap;

	public boolean add(String name, String phone, String email){

		if(phoneMap.containsKey(name)){
			phoneMap.put(name, new Info(phone,email));
			return true;
		}else{
			phoneMap.put(name, new Info(phone,email));
		}
		return false;
	}

	public String getPhone(String name){
		String phone = null;
		Info info = (Info)phoneMap.get(name);
		if(info == null){
			return null;
		}else{
			phone = info.getPhone();
		}
		return phone;
	}

	public String getEmail(String name){
		String email = null;
		Info info = (Info)phoneMap.get(name);
		if(info == null){
			return null;
		}else{
			email = info.getEmail();
		}

		System.out.println(email);
		return email;
	}

	public String[] findName(String phone){

		Set<String> mapSet  = phoneMap.keySet();
	    List<String> keyList = new ArrayList<String>();
		Iterator<String> it =  mapSet.iterator();
		while(it.hasNext()){
			String key = it.next();
			Info info = (Info)phoneMap.get(key);
			if(info.getPhone().equals(phone)){
				keyList.add(key);
			}
		}
		if(keyList.size() > 0){
			String[] retArray = new String[keyList.size()];
			for(int i=0;i<keyList.size();i++){
				retArray[i] = keyList.get(i);
			}
			return retArray;
		}
		return null;
	}

	public PhoneBook(){
		phoneMap = new HashMap<String,Info>();
	}


//	/**
//	 * @param args
//	 */
//	public static void main(String[] args) {
//		PhoneBook pb = new PhoneBook();
//		phoneMap.put("aaaa", new Info("11111","sss"));
//		phoneMap.put("bbbb", new Info("33333","sss"));
//		phoneMap.put("ccc", new Info("33333","gg"));
//		phoneMap.put("bbb", new Info("33333","e"));
//		String[] say = pb.findName("g");
//        for(int i=0;i<say.length;i++){
//        	System.out.println(say[i]);
//        }
//
//	}

}