import java.util.*;
public class MyMap {
/*Map没有继承Collection接口,其提供的是Key和Value映射*/
/*方法:
put(Object Key,Object Value)
get(Object Key)
containKey(Object Key)
containValue(Object V)
keySet()
values()
* */
/*HashMap:
HashMap基于哈希表的Map接口实现,提供null值和null键,但要保证键值唯一。
TreeMap不仅实现了Map接口,还实现了SortedMap接口,因此集合中的映射具有一定的顺序(按键值升序)。
但在增,删,定位时,TreeMap效率不如HashMap
* */
public static void main(String[] args) {
testMap();
}
public static void testMap(){
Stu stu1=new Stu("1同学",0);
Stu stu2=new Stu("2同学",1);
Stu stu3=new Stu("3同学",2);
Stu stu4=new Stu("4同学",3);
Stu stu5=new Stu("5同学",4);
Map<Integer,String> hashMap=new HashMap<>();
hashMap.put(stu1.id,stu1.name);
hashMap.put(stu5.id,stu5.name);
hashMap.put(stu3.id,stu3.name);
hashMap.put(stu4.id,stu4.name);
hashMap.put(stu2.id,stu2.name);
Set<Integer> set=hashMap.keySet();
Iterator<Integer> it=set.iterator();
while (it.hasNext())
{
int id=it.next();
System.out.println(id+":"+hashMap.get(id));
}
/*TreeMap*/
Map<Integer,String> treeMap=new TreeMap<>(hashMap);
Iterator<Integer> it2=treeMap.keySet().iterator();
while (it2.hasNext())
{
int id=it2.next();
System.out.println(id+":"+treeMap.get(id));
}
}
}
Java Map类代码复习总结
最新推荐文章于 2023-01-12 23:35:16 发布