1 Map与Collection并列存在。用于保存具有映射关系的数据:Key-Value,该组合称为entry
2 Map 中的 key 和 value 都可以是任何引用类型的数据
3 Map 中的 key 用Set来存放,不允许重复,即同一个 Map 对象所对应的类,须重写hashCode()和equals()方法。但是value之间可以重复
4 常用String类作为Map的“键”。
5 key 和 value 之间存在单向一对一关系,即通过指定的 key 总能找到唯一的、确定的 value。
package lianxi2; import java.util.HashMap; import java.util.Map; import org.junit.Test; /*1.HashMap:key是用Set存放的,不可存放,value是用Collection存放的,可以重复。一个key-value对,称为Entry, 所有Entry是由Set存放的,不可重复 2.向key当中添加元素时,调用key所在类的equals方法,判断key是否相同,若相同,则只能添加进后添加的元素 */ public class TestMap { @Test public void testMap(){ Map map = new HashMap(); map.put("ff", 322); map.put("aa", 322); map.put("aa", 323); map.put(null,null); map.put(new Student(1001,"sfa"), 234); map.put(new Student(1001,"sfa"), 234); System.out.println(map.size()); System.out.println(map); System.out.println(map.remove("ff")); //System.out.println(map.entrySet()); }
//遍历key值:不能用iterator,因为它适用于连续的集合
Set set = map.keySet();
for(Object i:set){
System.out.println(i);
}
//遍历value值
Collection coll = map.values();
Iterator ite = coll.iterator();
while(ite.hasNext()){
System.out.println(ite.next());
}
//遍历key-value值
Set set2 = map.entrySet();
for(Object i:set2){
Map.Entry m =(Map.Entry)i;
System.out.println(m.getKey()+"---->"+m.getValue());
}
}
结果:
4
{null=null, Student [id=1001, name=sfa]=234, ff=322, aa=323}
322
[null=null, Student [id=1001, name=sfa]=234, aa=323]
322
null
Student [id=1001, name=sfa]
aa
null
234
323
null---->null
Student [id=1001, name=sfa]---->234
aa---->323