一个cool map

好像是QuakeWang的东西, 本打算用在项目中.

还是备份在这吧:

import java.util.HashMap;

/**
 * Shortcut Map by extending HashMap.
 * You can use it as below:
 * map.put("country", "China", "city", "wuhan");
 * or
 * new QuickMap("country", "China", "city", "wuhan")
 * or
 * map.add("country", "China").add("city", "wuhan");
 * 
 * ablow is the same as old style:
 * map.put("country", "Chian")
 * map.put("city", "wuhan");
 * 
 * @author lichun
 *
 */

public class QuickMap extends HashMap<String, Object> 
{
	private static final long serialVersionUID = 1L;

	public QuickMap()
	{}
	
	/**
	 * 
	 * @param args
	 */
	public QuickMap(Object... args)
	{
		put(args);
	}
	
	/**
	 * shortcut method for put key-value in map.
	 * 
	 * @param args key-vlaue objects, the firt is key , the second is
	 * value, and so on.  
	 * @date Apr 22, 2009
	 * @auther Lichun
	 * @see
	 */
	public void put(Object... args)
	{
		for (int i = 1; i < args.length; i += 2) 
		{  
			put(String.valueOf(args[i - 1]), args[i]);  
		}  
	}
	
	/**
	 * shortcut method 
	 * @param key key in map
	 * @param value value in map
	 * @return a QuickMap instance , you can add next key-value.
	 * @date Apr 22, 2009
	 * @auther Lichun
	 * @see
	 */
	public QuickMap add(String key, Object value)
	{
		this.put(key, value);
		
		return this;
	}

}

用法及 testcase

public class QuickMapTest extends TestCase 
{
	public void testPut1()
	{
		QuickMap map = new QuickMap();
		map.put("firstName", "li", "lastName", "chunlei");
		String firstName = (String)map.get("firstName");
		assertTrue(firstName.equals("li"));
		String lastName = (String)map.get("lastName");
		assertTrue(lastName.equals("chunlei"));
	}
	
	public void testPut2()
	{
		QuickMap map = new QuickMap();
		map.put("firstName", "li", "lastName", "chunlei", "age");
		String firstName = (String)map.get("firstName");
		assertTrue(firstName.equals("li"));
		String lastName = (String)map.get("lastName");
		assertTrue(lastName.equals("chunlei"));
		
		assertNull(map.get("age"));
	}
	
	public void testAdd()
	{
		QuickMap map = new QuickMap();
		map.add("firstName", "li").add("lastName", "chunlei").add("age", 88);
		String firstName = (String)map.get("firstName");
		assertTrue(firstName.equals("li"));
		String lastName = (String)map.get("lastName");
		assertTrue(lastName.equals("chunlei"));
		int age = (Integer)map.get("age");
		assertTrue(age == 88);
	}

}
 

你可能感兴趣的:(快捷map hashmap)