前言
静态内部类的演示:
package day02;
import java.util.*;
@SuppressWarnings({"all"})
public class Fanxing {
public static void main(String[] args) {
Set<MyMap.MyEntry<String, Integer>> set3 = new HashSet<>();
}
}
class MyMap{
public static class MyEntry<K,V> {
}
}
若内部类支持泛型,就变成了myEntry的形式。
正文:
Map接口的常用方法:
void clear() //清空集合中所有的元素
//方法contains底层调用的是equals进行比对的,所以在进行调用是必须要重写equals方法。
boolean containsKey(Object key)//判断是否包含某个key
boolean containsValue(Object value)//判断是否包含某个value
Set<K> keySet() // 获取集合中的所有Key,且返回值类型Set集合
Set<Map.Entry<K,V>> entrySet()//将集合由map类型转换成Set型
/*
*Map集合通过entrySet方法将转化成Set集合,相当于向键值对合并成一个元素
*储存在Set集合中,并且每个元素的类型都是Map.Entry<K,V>(静态内部类,且支持泛型)
*/
V get(Object key)//通过key获取value
boolean isEmpty() //判断集合是否为空
V put(K key, V value) // 向集合中添加元素(键值对)
V remove(Object key)// 通过key删除key-value
int size() // 返回集合内键值对的数量
Collection<V> values() // 获取集合中的所有values,且返回值类型Collection集合
测试put方法:
package day03;
import java.util.HashMap;
import java.util.Map;
@SuppressWarnings({"all"})
public class MapSolutions {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
Integer i = new Integer(34);
map.put(i, "zhangsan");
map.put(1, "lisi");
map.put(new Integer(123), "zhaoliu");
map.put(321, "wangwu");
System.out.println(map.size());
System.out.println(map.isEmpty());
}
}
map集合的遍历:
- 先获取key,通过key获取value
package day03;
import java.util.*;
/**
* map集合的遍历:获取所有的key,通过key遍历value
*/
@SuppressWarnings({"all"})
public class MapTest02 {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(new Integer(1), "zahngsan");
map.put(2, "lisi");
map.put(3, "wangwu");
map.put(4, "zhaoliu");
map.put(5, "sunqi");
Collection<String> col = map.values();
Set<Integer> set = map.keySet();
Iterator<Integer> it = set.iterator();
while(it.hasNext()){
Integer i = it.next();
System.out.println(i + "==" + map.get(i));
}
System.out.println("====================================");
for(int s : set){
System.out.println(s + "==" + map.get(s));
}
}
}
- 遍历方式二:通过entrySet进行遍历:(高效)
package day03;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
@SuppressWarnings({"all"})
public class TestMap04 {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "zhangsan");
map.put(2, "lisi");
map.put(3, "wangwu");
map.put(4, "zhaoliu");
map.put(5, "sunqi");
Set<Map.Entry<Integer, String>> set = map.entrySet();
//返回值类型为Map.Entry<Integer, String>
Iterator<Map.Entry<Integer, String>> it = set.iterator();
while(it.hasNext()){
Map.Entry<Integer, String> node = it.next();
Integer Key = node.getKey();
String Value = node.getValue();
System.out.println(Key + "=" + Value);
}
}
}
将每一个键值对都封装成一个Entry对象储存在Set集合中,封装成功后可以调用Entry的实现类中的getValue和getKey取出被封装的Key和Value。