集合框架--10 Map
Map.Entry内存结构 Map集合的迭代方式
----------- android培训、java培训、java学习型技术博客、期待与您交流! ------------
1. Map.Entry接口
1). Map.Entry的含义
(1). 接口中接口
[1]. 接口中的成员也可以是接口 ----称为内部接口
[2]. 接口的内部接口的默认关键字:publicstatic [缺哪个,就补充哪一个]
示例代码:
public interface A {
interface B{}
public interface C{}
public static interface D{}
}
【MyEclipse验证】
【分析】
{1}. 可以别的类的方法中访问:所以内部接口B的public访问修饰符 被补充上
{2}. 可以通过“类名.”访问:所以内部接口B和C的static静态修饰符 被补充上
[3]. 接口中成员的默认关键字【总结】
{1}. 具有1个默认关键字的成员:成员方法 public
{2}. 具有2个默认关键字的成员:成员接口 public static
{3}. 具有3个默认关键字的成员:成员变量 public static final ------实际是全局常量
(2). Map.Entry的基本概念
[1]. Map是接口,则Entry是Map中的成员
[2]. Entry实际上是Map接口中的内部成员接口。
源码如下:
public interface Map<K,V> {
…
//***成员内部接口 ----默认是public static
interface Entry<K,V> {
//获取
K getKey();
V getValue();
//修改
V setValue(V value);
boolean equals(Object o);
int hashCode();
}
}
[3]. Entry的含义
Entry代表一个键值对Key和Value之间的关系
[4]. Entry设计成Map的内部类的原因
由于Entry本身代表一个键值对的键和值之间的关系,所以Entry必须能够访问一个键值对的Key和Value。所以,Entry设计成Map的内部类,从而可以直接访问Map内部成员。
[5]. Map和Entry之间的先后顺序关系:
先有Map,再有Entry
(3). Map.Entry中的方法
[1]. 查/获取
{1}.获取一个Key:K getKey(); //key的getter
{2}. 获取一个Value:K getValue(); //value的getter
[2]. 改/设置
{3}. 设置一个Value:V setValue(Vvalue); //value的setter
【注意】Entry中没有key的setter。setKey()方法不存在。
【助记】由于Entry是表示一个键值对中key和value之间的关系,所以必须能够访问和修改key和value。所以就有key和value的setter和getter:set/getKey( ) 和set/getValue( )
由于Map中的key是唯一的,不能随便修改,所以Entry中没有提供setKey()方法
(4). Map和Map.Entry中获取方法的区别:
Map中:V get (Objectkey) 通过键Key 获取值Value
Map.Entry中:K getKey()和V getValue() 获取键和值
2. Map.Entry内存示意图
1). Map内存示意图
(1). 示例代码
Map<String, String> map =new HashMap<String, String>();
map.put("01", "zs1");
map.put("02", "zs2");
map.put("03", "zs3");
map.put("04", "zs4");
//Map被转换为Map.Entry
Set<Map.Entry<String, String>> entrySet=map.entrySet();
(2). Map和Map.Entry的内存示意图
3. Map元素的迭代方式
【注意】Map没有迭代器
(1). Map的两种迭代器方式
【Map的迭代原理】
通过不同的方式(2种) 把Map转化成Set集合,通过Set的Iterator对Set进行迭代。迭代的过程中,获取Map中相应的key和value
[1]. 将Map的所有key映射为Key构成的Key Set
[2]. 将Map的所有key-value映射为键值对关系构成的Entry Set
(2). Map迭代方式I----Key Set 示例代码
Map<String, String> map =new HashMap<String, String>();
map.put("01", "zhangsan1");
map.put("02", "zhangsan2");
map.put("03", "zhangsan3");
map.put("04", "zhangsan4");
//遍历
Set<String> keySet =map.keySet();
Iterator<String> it =keySet.iterator();
while(it.hasNext()){
Stringkey =it.next();
Stringvalue =map.get(key);
sop("key ="+key +"-------value ="+value);
}
(3). Map迭代方式II----Entry Set 示例代码
Map<String, String> map =new HashMap<String, String>();
map.put("01", "zhangsan1");
map.put("02", "zhangsan2");
map.put("03", "zhangsan3");
map.put("04", "zhangsan4");
Set<Map.Entry<String, String>> entrySet =map.entrySet();
Iterator<Map.Entry<String, String>>it =entrySet.iterator();
while(it.hasNext()){
Map.Entry<String,String> relation =it.next();
Stringkey =relation.getKey();
Stringvalue =relation.getValue();
sop(key+"::" + value);
}
----------- android培训、java培训、java学习型技术博客、期待与您交流! ------------