在java的Map集合中如何使用HashMap类?

2025-03-05 07:18:54
推荐回答(2个)
回答1:

Map map=new HashMap();//实例化map对象map.put("key","value");//存放值(值以键(key)-值(value)方式存放。)System.out.print(map.get("key").toString());//取值 根据键就可以取到值

回答2:

import java.util.*;public class TestMap{
public static void main(String []args){
Map m1 = new HashMap();
Map m2 = new TreeMap();
m1.put("one",1); //对象自动打包和解包
//m1.put("one",new Integer(1))
m1.put("Two",2);
//m1.put("one",new Integer(2))
m1.put("Three",3);
m2.put("A",4);
m2.put("B",5);
System.out.println(m1.size());
System.out.println(m1.containsKey("one")); //是否存在键值对应,返回True flase
System.out.println(m1.containsValue(4));
if(m1.containsKey("Two")){
int i = ((Integer)m1.get("Two")).intValue();
System.out.println(i);
}
Map m3 = new HashMap(m1); //父类引用指向子类对象
m3.putAll(m2); //将M2对象添加到M3
System.out.println(m3);
}
} 你自己先看下