Map

 

Map:以键值对的形式存入,必须要保证键的唯一性。

    添加:put(key,value):

如果存入已有的键,会发生值覆盖的情况。

    判断:containsKey(key),containsValue(value)

    删除:remove(key)

    个数:size();

    取出:get(key)

当返回为null时,对于HashMap有两种情况,一,该键不存在,二,该键存在对应的值是null。

    取出所有元素:

原理:将Map集合转成Set集合。在通过迭代器取出。

keySet():将Map集合中的所有键取出存入到了Set集合中,在通过迭代器遍历,在遍历过程中,

使用Map集合的get方法取出键所对应的值。

 

entrySet():将Map集合中的键值映射关系取出,被封装成了Map.Entry对象。并将Map.Entry对象存入到了Set集合中。

  通过迭代器取出Map.Entry 对象,并通过该对象的getKey(),getValue()方法取出map集合中的键和值。

 

    取出所有值:values();

|--HashMap:数据结构是哈希表,线程是不安全的,可以存入null键null值。

|--HashTable:数据结构是哈希表,线程是安全的,不可以存入null键null值,被HashMap所取代。

|--TreeMap:数据结构是二叉树,线程是不安全的,可以对Map集合中的键进行排序。

 

什么时候使用Map集合呢?

当分析问题时,对象间出现了映射关系时,就要先想到Map集合。

 

练习:获取字符串中,每一个字母出现的次数。要求结果是:a(3)b(1)....;

 

public String getCharCount(String str)

{

char[] chs = str.toCharArray();

 

int count = 0;

 

TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();

 

for(int x=0; x<chs.length; x++)

{

if(!(chs[x]>='a' && chs[x]<='z'))

continue;

Integer i = tm.get(chs[x]);

/*

if(i==null)

count++;

else

{

count = i;

count++;

}

*/

 

if(i!=null)

count = i;

count++;

tm.put(chs[x],count);

}

 

StringBuilder sb = new StringBuilder();

 

Iterator<Map.Entry<Character,Integer>> it = tm.entrySet().iterator();

 

while(it.hasNext())

{

Map.Entry<Character,Integer> me = it.next();

Character ch = me.getKey();

Integer x = me.getValue();

sb.append(ch+"("+x+")");

}

 

return sb.toString();

}

 

 

你可能感兴趣的:(map)