- 1、为什么要有泛型?
- 2、泛型的概念?
- 3、为什么要使用泛型?
- 3.1、类型不安全
- 4、在集合中使用泛型
- 4.1、ArrayList集合
- 4.2、Map集合
- 5、 在集合中使用泛型
@Test
public void test02(){
ArrayList list = new ArrayList();
list.add(123);
list.add(345);
list.add(456);
//编译时就会进行类型检查,保证数据安全
// list.add("Tom");
for(Integer score : list){
//避免了强转操作
int stuScore = score;
System.out.println(stuScore);
}
}
4.2、Map集合
@Test
public void test03(){
Map map = new HashMap();
map.put("Tom",123);
map.put("Jack",456);
map.put("Rose",789);
Set> set = map.entrySet();
Iterator> iterator = set.iterator();
while(iterator.hasNext()){
Map.Entry m = iterator.next();
String key = m.getKey();
Integer value = m.getValue();
System.out.println(key+"------->"+value);
}
}
5、 在集合中使用泛型
- ① 集合接口或集合类在jdk1.5时都修改为待泛型的结构
- ②在实例化集合类时,可以指明具体的泛型类型
- ③指明完以后,在集合或者接口中凡是定义类或者接口时,内部结构(比如:方法、构造器、属性等)使用到类的泛型的位置,都指定为实例化的泛型类型;
比如:add(E e)—>思力华以后:add(Integer e) - ④注意点:泛型的类型必须是类,不能是基本数据类型,需要永奥基本数据类型的位置,拿包装类替换
- ⑤如果实例化时。没有指明泛型的类型。默认类型为java.lang.Object类型。



