泛型 + HashMap:
编译时期进行类型检查和类型推断的特性(泛型只支持引用数据类型,不支持基本数据类型)
定义:
类型 对象 = new 类型 ();
泛型类:
具有一个或多个类型 参数的类
访问修饰符 class classname{}
创建泛型类实例:
new classname(argList);
泛型限定:
a< ? extends E> 前面可以是E本身或其子类
a< ? super E> 前面可以是E本身或其父类
a< ? > 任意类型
泛型擦除:
泛型只能编译阶段有效,一旦编译成字节 码,字节码中是不包含泛型的。
泛型工作在编译阶段的,一旦程序编译成class文件,class文件中就不存在泛型了,这就是泛型擦除。
Map集合:
无序,不重复,无索引
键不能重复,值可以重复,每个键只能找到自己对应的值
hashMap:
无序,不重复,无索引,允许null
构造4种:
HashMap()
HashMap(int initialCapacity)
HashMap(int initialCapacity, float loadFactor)
HashMap(Map<? extends K,? extends V> m)
遍历三种方式:
- keySet
- entrySet
- forEach
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
public class MapExample {
public static void main(String[] args) {
HashMap<String,String> map = new HashMap();
map.put("1","one");
map.put("2","two");
map.put("3","three");
map.put("4","four");
map.put("5","");
map.put(null,"five");
System.out.println("**********keySet*********");
Set<String> key = map.keySet();
for (String s:key) {
String v = map.get(s);
System.out.print("键:" + s);
System.out.println("值:" + v );
}
//key不存在,或key存在映射为null,return为null,不会添加,return为其他会映射
map.computeIfAbsent("5", new Function<String, String>() {
@Override
public String apply(String s) {
System.out.println(s);
return null;
}
});
System.out.println(map.get("5"));
//若key存在并且映射非空,return为null,会删除该映射,return为其他,会替换value
map.computeIfPresent("6", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
return ",ok";
}
});
System.out.println("**********entrySet*********");
Set<Map.Entry<String,String>> set = map.entrySet();
for (Map.Entry<String,String> entry:set) {
String k = entry.getKey();
String v = entry.getValue();
//String v = map.get(k);
System.out.print("键:" + k + " ");
System.out.println("值:" + v);
}
System.out.println("**********forEach*********");
map.forEach(new BiConsumer<String, String>() {
@Override
public void accept(String s, String s2) {
System.out.print("键:" + s + " ");
System.out.println("值:" + s2);
}
});
}
}
方法:
remove() 不存在返回null,存在删除
重写equals方法:
containskey() //返回boolean
containsvalue() //返回值
不能通过get(key) == null 是否存在