转自:http://www.apkway.com/thread-2414-1-1.html 稍做修改
一、HashMapDemo类用于构建需要放进Map中的对象
package hashmap;
public class HashMapDemo {
private String name;
private String school;
public HashMapDemo(String name,String school){
this.name=name;
this.school = school;
}
public String toString(){
return school+"毕业的"+name;
}
}
二、用于测式HashMap类中的对象
package hashmap;
import java.util.HashMap;
import java.util.Map;
public class HashMapTest {
public static void main(String[] args) {
HashMapDemo stu1=new HashMapDemo("李明","北京中心");
HashMapDemo stu2 = new HashMapDemo("刘丽","天津中心");
Map students=new HashMap();
//把英文名称与学员对象按照"键-值对"的方式存储在HashMap中
students.put("Jack", stu1);
students.put("rose", stu2);
//分别打印键集、值集、以及键-值对集合
System.out.println("键集:"+students.keySet());
System.out.println("值集:"+students.values());
System.out.println("键-值对集合:"+students);
String key="Jack";
//判断是否存在某个键,如果是同,则根据键获取相应的值
if(students.containsKey(key)){
System.out.println(students.get(key));
}
//根据键删除某个值
students.remove(key);
System.out.println(students);
}
}
总结:
2、获取键集使用Map 对象.keySet()方法。
获取值集使用Map对象.values()方法。
获取键-值对集合直接使用Map对象。
3、判断是否存在某个键用 Map对象.containsKey(键)方法。
判断是否存在某个值用 Map对象.containsValue(值)方法。
4、获取某个键所对应的值使用Map 对象.get(键)方法。
5、根据键删除Map对象中某个对象使用Map 对象.remove(键)方法。
删除所有数据使用Map对象.clear()方法。
比较简单,不再一一罗列......详细请看以下:
abstract void |
clear()
Removes all elements from this
Map , leaving it empty.
|
abstract boolean |
containsKey(
Object key)
Returns whether this
Map contains the specified key.
|
abstract boolean |
containsValue(
Object value)
Returns whether this
Map contains the specified value.
|
abstract Set< Entry<K, V>> |
entrySet()
Returns a
Set containing all of the mappings in this
Map .
|
abstract boolean |
equals(
Object object)
Compares the argument to the receiver, and returns
true if the specified object is a
Map and both
Map s contain the same mappings.
|
abstract V |
get(
Object key)
Returns the value of the mapping with the specified key.
|
abstract int |
hashCode()
Returns an integer hash code for the receiver.
|
abstract boolean |
isEmpty()
Returns whether this map is empty.
|
abstract Set<K> |
keySet()
Returns a set of the keys contained in this
Map .
|
abstract V |
put(K key, V value)
Maps the specified key to the specified value.
|
abstract void |
putAll(
Map<? extends K, ? extends V> map)
Copies every mapping in the specified
Map to this
Map .
|
abstract V |
remove(
Object key)
Removes a mapping with the specified key from this
Map .
|
abstract int |
size()
Returns the number of mappings in this
Map .
|
abstract Collection<V> |
values()
Returns a
Collection of the values contained in this
Map .
|