您的位置:首页 > 其它

HashMap的使用方法及注意事项

2013-09-25 19:56 971 查看
99、Map(映射):Map 的keySet()方法会返回 key 的集合,因为 Map 的键是不能重复的,因此 keySet()方法的返回类型是 Set;而 Map 的值是可以重复的,因此 values()方法的返回类型是 Collection,可以容纳重复的元素。

100、Map注意事项:

A)

public class TestMap {

publicstatic void main(String[] args) {

HashMap map = new HashMap();

map.put("a","zhangsan");

map.put("b","lisi");

map.put("c","wangwu");

map.put("a","cuijun");

//System.out.println(map);

String value = (String)map.get("a");

System.out.println(value);

System.out.println("---------------------");

Stringvalue1 = (String)map.get("d");

System.out.println(value1);

}

}


由上述代码可知不可以重复。

B)

public classTestMap1 {

publicstatic void main(String[] args) {

HashMap map = new HashMap();

String str = newString("cuijun");

map.put("a",str);

map.put("b",str);

//map.put("a", "cuijun");

//map.put("b", "cuijun");

System.out.println(map);

}

}


由上述代码可知可以重复。

注:因此 keySet()方法的返回类型是 Set,values()方法的返回类型是 Collection。

101、关于HashSet的使用:

A)

public class TestMap2 {

publicstatic void main(String[] args) {

HashMap map = new HashMap();

map.put("a","aa");

map.put("b","bb");

map.put("c","cc");

map.put("d","dd");

Set keys = map.keySet();//使用keySet()方法,获取键的集合

for(Iterator it =keys.iterator(); it.hasNext();){

String key = (String)it.next();

String value = (String)map.get(key);

System.out.println(key+"="+value);

}

}

}


b)

publicclass TestMap3 {

publicstatic void main(String[] args) {

HashMap map = new HashMap();

map.put("a","aa");

map.put("b","bb");

map.put("c","cc");

map.put("d","dd");

Set keys = map.entrySet();//使用entrySet()方法,获取entry对象的集合

for(Iterator it =keys.iterator(); it.hasNext();){

Map.Entry maps = (Map.Entry)it.next();//Map.Entry:Entry是Map的一个内部类。具体详情请参考API。

/*

* 关于内部类的简单介绍:内部类是定义在类内部的类

* public class A{

*      publicclass B{}

* }

* A a = new A();

* A.B b = new A.B();

*/

String key = (String)maps.getKey();

String value = (String)maps.getValue();

System.out.println(key+":"+value);

}

}

}


附Map.Entry的API简介:

Map.entrySet方法返回映射的 collection视图,其中的元素属于此类。获得映射项引用的唯一方法是通过此 collection视图的迭代器来实现。这些Map.Entry对象仅在迭代期间有效;更确切地讲,如果在迭代器返回项之后修改了底层映射,则某些映射项的行为是不确定的,除了通过setValue在映射项上执行操作之外。

C)通过使用HashSet判断输入值的个数

publicclassTestMap4 {

publicstatic void main(String[] args) {

HashMap map = new HashMap();

for(int i = 0; i < args.length; i++){

if(map.get(args[i]) ==null){

map.put(args[i],newInteger(1));

}else{

Integer value = (Integer)map.get(args[i]);

value =  new Integer(value.intValue()+1);

map.put(args[i],value);

}

}

Set keys = map.keySet();

for(Iterator it =keys.iterator(); it.hasNext();){

String key = (String)it.next();

Integer value = (Integer)map.get(key);

System.out.println(key+"="+value);

}

}

}


=====================关于HashSet其实运行下这些代码,参考着API是很容易理解的=============
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: